Forbid dynamic arrays in boolean evaluation contexts

Jonathan M Davis jmdavisProg at gmx.com
Mon Mar 25 10:39:01 PDT 2013


On Monday, March 25, 2013 10:29:46 H. S. Teoh wrote:
> 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.

You can rely on null being null, and you can rely on any array that you've
explictly set to null being null as long as no other mutating operations
are used on it. That's guaranteed.

> 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.

It can be valuable to have a function which returns an array specifically 
return null to indicate something, and I believe that Phobos does this in some 
places. But that's about the only place that it's safe to rely on an array 
being null, as it returned null explicitly. It's relying on an array being
null when it was not explicitly set to null which doesn't work.

- Jonathan M Davis


More information about the Digitalmars-d mailing list