determining if array element is null
Neia Neutuladh
neia at ikeran.org
Sat Jun 2 18:35:59 UTC 2018
On Saturday, 2 June 2018 at 18:10:38 UTC, eastanon wrote:
> Does D array implementation support an array of null values?
>
> int a[4] = null;
>
> But I ran into a type error while checking if a[i] is null
>
> foreach(i; 0..3){
> if(i == null){
> writeln("it is null");
> }
> }
> }
>
> How do you set fixed size array of null values and check if
> they are null?
There are several problems with your code.
1. `int a[4]` should be `int[4] a`. You probably see a warning
about using the C-style array syntax.
2. `int[4] a = null` treats the initialization as a copy from an
array whose value is null. If you run just that line of code, it
will produce an error at runtime: "object.Error@(0): Array
lengths don't match for copy: 0 != 4"
If you want to initialize every member of an array with a value,
you write it as:
int[4] a;
a[] = 5;
3. `foreach (i; 0..3)` will iterate through a range of integers:
0, 1, and 2. You haven't touched your array.
4. `i == null` is trying to compare an integer, which can never
be null, to null. You either want to use std.typecons.Nullable
(if you just want integers-that-might-be-null) or an array of
pointers to integers (if you want reference semantics).
5. Usually, you want to use `i is null` instead of `i == null`.
More information about the Digitalmars-d-learn
mailing list