Just a friendly reminder about using arrays in boolean conditions

Jonathan M Davis newsgroup.d at jmdavisprog.com
Mon Nov 25 09:53:13 UTC 2024


On Monday, November 25, 2024 1:57:36 AM MST Walter Bright via Digitalmars-d 
wrote:
> I neglected to mention that:
>
> ```
> if (a)
> ```
>
> is equivalent to:
>
> ```
> if (a.ptr && a.length)
> ```

The core problem is that ptr is checked at all. Whether it's null or not is
absolutely irrelevant to almost all D code. All that matters is length,
because if length is 0, then you cannot dereference any elements, because
there are none, and if length is non-zero, then there are elements there to
be dereferenced. Either way, the ptr will only be dereferenced if there are
elements to dereference, and thus whether it's null or not is irrelevant.

So, fundamentally, the check for null makes no sense even if it would have
made sense with a C array, because a C array is just a naked pointer and has
no language protections to ensure that you don't dereference it when it
doesn't have elements. D arrays have those protections.

And routinely, when programmers use `if(arr)`, they seem to expect that it
will check for `if(arr.length)` - to the point that even if checking for
null arrays did make sense, I'd still consider `if(arr)` to be a code smell,
because it's misunderstood so frequently that outside of a D expert, I
cannot trust that the programmer who wrote it understood what they were
doing, and even with a D expert, I would wonder if they'd made a mistake,
since we all do that from time to time.

I started this thread precisely because I ran into a bug at work that was
caused by this misunderstanding - and it was written my someone who has
worked on Phobos before. So, I figured that I should remind folks of the
issue in the hopes that it would be made less often - though ideally, we'd
just deprecate using arrays directly in boolean conditions, because the
current behavior is too error-prone.

- Jonathan M Davis





More information about the Digitalmars-d mailing list