Just a friendly reminder about using arrays in boolean conditions
kdevel
kdevel at vogtner.de
Thu Nov 28 21:51:27 UTC 2024
On Wednesday, 27 November 2024 at 06:46:18 UTC, Jonathan M Davis
wrote:
> [...] Either way, I would consider it good practice to be
> explicit about testing for null vs empty instead of if(arr),
> because if(arr) is misunderstood so frequently that the odds
> are very high that the programmer who wrote the code
> misunderstood what they were actually testing. And even if they
> didn't, you have no way of knowing that when reading their
> code. On the other hand, code like
> [line breaks inserted]
>
> if(arr !is null)
That translates into broken English "if array not is null". More
idiomatic and more readable is
if (arr.ptr)
But wait, that's not the same!
import std;
void main ()
{
auto arr = typeid (int).initializer;
writeln (arr ! is null); // true
writeln (arr.ptr); // null
writeln (arr.length); // 4
writeln (arr.empty); // false
writeln (arr ? true : false); // true
writeln (arr); // segfault
}
It appears to me that if (arr !is null) and if (arr) are
equivalent.
More information about the Digitalmars-d
mailing list