Is empty array null?

Jonathan M Davis jmdavisProg at gmx.com
Mon Feb 27 14:06:48 PST 2012


On Monday, February 27, 2012 17:44:40 Pedro Lacerda wrote:
> The expression "[] is null" evaluates to true here using 2.058, but I
> expected to be false. What am I missing?

Arrays treat null kind of funny. For equality, null is considered to be the 
same as an array with length 0. So,

int[] a;
assert(a.length == 0);
assert(a == null);

If you want to specifically check that an array's ptr property is null, then 
you can use is:

int[] a;
assert(a is null);

Where the difference tends to come in is if an array was allocated and then 
shrunk down to length 0:

int a[];
assert(a.length == 0);
assert(a == null);
assert(a is null);
a.length = 5;
a.length = 0;
assert(a.length == 0);
assert(a == null);
assert(a !is null);

But because null and empty aren't really treated differently for the most part, 
it's generally unwise to care about null and empty being different for arrays. 
A possible exception is a function which specifically returns a null array 
under some set of circumstances (IIRC some functions in std.path do this). But 
the wisdom of even that is debatable.

As for null vs [], I'm not aware of the spec really specifying whether "[] is 
null" or not. "[] == null" is definitely guaranteed, but I think that it may 
have even changed before whether "[] is null" is true or not. But it may be 
defined in the spec, I don't know. Certainly, I don't find it surprising that 
"[] is null", simply because it's more efficient (since then no memory has to be 
allocated to the array's ptr property), and the differences between null and 
empty are largely ignored for arrays anyway.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list