How to check whether an empty array variable is null?

Meta via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Oct 10 08:46:49 PDT 2015


On Saturday, 10 October 2015 at 15:20:04 UTC, tcak wrote:
> [code]
> 	int[] list;
>
> 	list = new int[0];
>
> 	std.stdio.writeln("Is Null ? ", (list is null));
> [/code]
>
> Result is "Is Null? true".
>
> Is this the correct behaviour? I would expect compiler to point 
> to an address in the heap, but set the length as 0. So, it 
> wouldn't return null, but the length would be 0 only.

Yes, it's correct behaviour. `array is null` checks whether 
array.ptr is null, which is the case for a 0-length array.

void main()
{
	auto a = new int[0];
	writeln(a.ptr);      //a.ptr is null
	
	auto a2 = new int[1];
	writeln(a2.ptr); //a2.ptr is not null
	a2 = a[0..$];    //Slice off the only element of a2
	writeln(a2.ptr); //Now a2.ptr is null
}


More information about the Digitalmars-d-learn mailing list