Just a friendly reminder about using arrays in boolean conditions

deadalnix deadalnix at gmail.com
Fri Nov 29 10:10:58 UTC 2024


On Monday, 25 November 2024 at 09:53:13 UTC, Jonathan M Davis 
wrote:
> 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.
>

IMO there is a stronger case.

When converting to bool, we typically use value rather than 
identity, everywhere in the language, except for arrays. Checking 
for the pointer of the array is an identity operation. Checking 
for the length and/or the content is value operation.

This is the correct one.

This null check for arrays is a major footgun. And it is easy to 
check for when wanted using the `is` operator.


More information about the Digitalmars-d mailing list