Just a friendly reminder about using arrays in boolean conditions
user1234
user1234 at 12.de
Mon Nov 18 12:20:17 UTC 2024
On Sunday, 17 November 2024 at 08:57:35 UTC, Jonathan M Davis
wrote:
> 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.
Well I agree, even if that will take years to have .length tested
instead of .ptr.
Little story however: I've encountered a case where the explict
check was also wrong.
```d
module runnable;
import std.stdio;
void v(string s)
{
if (s.length) writeln("case length :`", s, "`");
else if (s is null) writeln("case null :`", s, "`");
else writeln("case not null but no
length:`", s, "`");
}
void main(string[] args)
{
v("hello");
v(null);
v("");
}
```
The different semantics between `null` and `""` for strings is
well illustrated here I'd say.
More information about the Digitalmars-d
mailing list