Thread overview
determining if array element is null
Jun 02, 2018
eastanon
Jun 02, 2018
Neia Neutuladh
Jun 02, 2018
ag0aep6g
Jun 05, 2018
Timoses
Jun 05, 2018
Alex
June 02, 2018
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?


June 02, 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`.
June 02, 2018
On 06/02/2018 08:35 PM, Neia Neutuladh wrote:
> 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;

`int[4] a = 5;` is fine, too.
June 05, 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?

Does `int[4] nums = void` work?
June 05, 2018
On Tuesday, 5 June 2018 at 14:52:28 UTC, Timoses wrote:
> Does `int[4] nums = void` work?

Work for what?

If you avoid initialization, then the variable(s) are not initialized.

https://dlang.org/spec/declaration.html#void_init


However, an int is not nullable and always contains a value.