Just a friendly reminder about using arrays in boolean conditions

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sun Nov 17 08:57:35 UTC 2024


Just a friendly reminder with regards to arrays and using them in if
conditions, assertions, etc. - the language unfortunately checks that
they're non-null - like pointers - rather than non-empty like many people
seem to expect.

I just had to fix a bug at work that was caused by someone using strings in
boolean conditions where the code was clearly supposed to be checking for
empty strings - e.g `if(!str)` and `str ? result1 : result2`
- and it broke when some code started giving it empty strings instead of
null strings.

>From what I've seen in discussions on this in the past, many people
misunderstand how this works and think that using arrays as boolean
conditions checks for non-empty when in fact it checks whether the ptr field
is non-null. This matches the behavior for pointers but is almost never what
you actually want to do with arrays, because it's almost never a good idea
to distinguish between null arrays and empty arrays, since it's quite
error-prone (e.g. `"".idup is null` is true). And to make matters worse,
because it's so frequently misunderstood, even if you do have a use case
where it makes sense to check for non-null, it's almost never a good idea to
do it implicitly instead of using !is null simply because without being
explicit about it, there's pretty much no way that anyone else reading the
code is going to know that the author actually meant to check for non-null
instead of misunderstanding how the language feature works, since the odds
are much higher that they misunderstood.

Personally, I'd love to see using arrays in boolean conditions simply be
deprecated and then made an error (and maybe changed to check for empty at
some point in the future if we want to), since it's often used incorrectly,
and even when it is used correctly, it's pretty much always a good idea to
do an explicit check instead of an implicit one so that it's clear to anyone
else reading the code what you meant to check for.

In any case, given that I just ran into this issue in production code, and
that it's something that seems to be frequently misunderstood, I thought
that I'd bring it up as a reminder in the hopes that more people would
understand the actual behavior and not make this mistake.

- Jonathan M Davis





More information about the Digitalmars-d mailing list