is ==

Jonathan M Davis newsgroup.d at
Sun May 20 00:32:42 UTC 2018

On Saturday, May 19, 2018 17:13:36 Neia Neutuladh via Digitalmars-d-learn 
> I don't think I've ever wanted to distinguish a zero-length slice
> of an array from a null array.

It's safer if you don't, because it's so easy to end up with a dynamic array
that is empty instead of null, and stuff like == doesn't care about the
difference. But there is code that's written that cares (e.g. IIRC,
std.experimental.allocator does in some cases).


is equivalent to


and casting a dynamic array to bool is equivalent to

arr !is null

which means that



if(arr !is null)

whereas it's not uncommon for folks to think that it means

if(arr.length != 0)



is ultimately equivalent to

asser(arr !is null);

which suprises many folks and is rarely what folks want. So, there was a
push at one point to make it illegal to use a dynamic array in an if
statment or assertion directly, and it did briefly make it into the
compiler. However, a few folks (Andrei and Vladimir in particular IIRC), had
used arrays in if statments directly quite a bit, knowing full well what it
meant. So, their code was right (albeit potentially confusing), and they
pushed back. So, the change was reverted, and we're still stuck with the
error-prone situation that we've had.

So, most of us would argue that it's risky to treat null dynamic arrays as
special and that it should be done with caution, but programmers who know
what they're definitely do it. Unfortunately, when you read code that's
writen that way, it's usually hard to tell whether it was written with that
undertanding or not, and a stray == in the code could easily break it.

> As I already said, I use "array.length == 0". "array.empty" is
> part of that newfangled range business.

LOL. Well, if you stay away from ranges, you're losing out on a lot of
benefits - including large portions of the standard library, but checking
for length works fine if you're dealing with code that's just using dynamic
arrays and not ranges. The key thing is to avoid arr == null, because that's
were the bugs lie.

- Jonathan M Davis

More information about the Digitalmars-d-learn mailing list