Just a friendly reminder about using arrays in boolean conditions
Dom DiSc
dominikus at scherkl.de
Mon Nov 18 15:39:38 UTC 2024
On Monday, 18 November 2024 at 12:24:01 UTC, user1234 wrote:
>> ```d
>> 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, "`");
>> }
One should always first check for null and then for length. This
should be immediately clear, as asking for a length doesn't make
sense if something is null.
Ok, an array has both a pointer and a length, but I would never
expect the length to contain something useful, if the pointer is
not assigned a legal address.
If I were to implement arrays, I would use a simple pointer, and
length would be the first element of the allocated block. For any
object, I have always in mind that it could be implemented in
this way, so would never access anything as long as the pointer
is not checked first.
More information about the Digitalmars-d
mailing list