Forbid dynamic arrays in boolean evaluation contexts

Jonathan M Davis jmdavisProg at gmx.com
Mon Mar 25 10:32:36 PDT 2013


On Monday, March 25, 2013 18:18:00 Phil Lavoie wrote:
> Nothing is wrong with that apparently. I was not aware arr.length
> tolerated null slices. Does it keeps its behavior in unsafe or
> system mode?

If you haven't read this article on arrays, then you should:

http://dlang.org/d-array-article.html

An array in D is basically (though not exactly)

struct A(T)
{
 A ptr;
 size_t length;
}

Almost nothing cares about if ptr is null. If you're checking length, then it 
just checks length (which is 0 if ptr is null). If you append to it or set 
length, then the runtime will look at ptr and allocate or reallocate it if it 
needs to (or just increase length if it can do so). == does something along 
the lines of

if(lhs.length != rhs.length)
 return false;
if(lhs.ptr is rhs.ptr)
 return true;
for(size_t i = 0; i < lhs.length; ++i)
{
 if(lhs[i] != rhs[i])
 return false;
}
return true;

So, it doesn't care one whit whether ptr is null or not. Almost nothing cares. 
About the only thing that cares is the is operator - i.e. arr is null. 
However, the problem here is that cast(bool)arr returns whether arr.ptr is 
null rather than arr.length == 0, which is inconsistent with almost everything 
else that goes on with arrays, and so it's error-prone.

- Jonathan M Davis


More information about the Digitalmars-d mailing list