char[] == null

Meta via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Nov 18 19:53:46 PST 2015


On Wednesday, 18 November 2015 at 23:53:01 UTC, Chris Wright 
wrote:
> ---
> char[] buffer;
> if (buffer.length == 0) {}
> ---

This is not true. Consider the following code:

import std.stdio;

void main()
{
	int[] a = [0, 1, 2];
         //4002E000 3
	writeln(a.ptr, " ", a.length);
         //Is not triggered, obviously
         assert(a == null);
	
	a.length = 0;
         //4002E000 0
	writeln(a.ptr, " ", a.length, " ", a);
         //Is not triggered, not as obvious
         assert(a == null);
}

There are cases when an array may have 0 length but a non-null 
pointer. If you want to check if an array's length is 0, you must 
explicitly check its length member. Checking if an array is equal 
to null only compares its pointer field to null. It does *not* 
check the length.


More information about the Digitalmars-d-learn mailing list