Forbid dynamic arrays in boolean evaluation contexts

H. S. Teoh hsteoh at quickfur.ath.cx
Mon Mar 25 10:29:46 PDT 2013


On Mon, Mar 25, 2013 at 01:15:59PM -0400, Jonathan M Davis wrote:
> On Monday, March 25, 2013 17:43:24 Phil Lavoie wrote:
> > I do believe that, in any case, this form is best:
> > if( arr !is null && !arr.empty )
> 
> That's utterly pointless. empty checks that length == 0, and length ==
> 0 if the array is null. It can be useful to check whether an array is
> null with the is operator for cases where that's used to indicate that
> a result wasn't found or something like that, but very little cares
> about the difference between a null array and an empty one, and
> attempting to treat them as different tends to be very error-prone.
> 
> I don't really like how null works with arrays, since it's generally
> treated as the same as an empty array (including for ==), but that's
> the way it works in D, and you just have to deal with it. And given
> how arrays in D work in general, having if(arr) check specifically for
> null rather than empty is definitely error-prone.
[...]

I think this is all just a storm in a teacup. Just use .length:

	import std.stdio;

	void main() {
		int[] a;
		writeln(a is null);	// prints true
		writeln(a.length);	// prints 0

		a ~= 1;
		a.length = 0;
		writeln(a is null);	// prints false
		writeln(a.length);	// prints 0
	}

So just use "if (a.length > 0)" and you're fine.

The distinction between null and non-null for arrays is, IMO, an
implementation-specific detail that should not be relied upon. In my
mind, it's the implementation that gets to decide when an array should
be null and when it shouldn't. User code had better not be dependent on
that kind of detail. If you *really* need to tell the difference, just
use Nullable to wrap around the array.


T

-- 
English has the lovely word "defenestrate", meaning "to execute by
throwing someone out a window", or more recently "to remove Windows from
a computer and replace it with something useful". :-) -- John Cowan


More information about the Digitalmars-d mailing list