null == "" is true?

Paul Backus snarwin at gmail.com
Tue Jul 12 18:56:43 UTC 2022


On Tuesday, 12 July 2022 at 16:40:38 UTC, H. S. Teoh wrote:
> Because an empty string is, by default, represented by an empty 
> slice of the null pointer.
>
> Do not rely on this, however; it's possible sometimes to get an 
> empty string that isn't null, e.g., if you incrementally shrink 
> a slice over a string until it's empty. In that case, .ptr will 
> not be null, but the string will still be empty.  Always 
> compare strings against "" rather than null, because the latter 
> may not do what you think it does sometimes.

This is actually 100% reliable when comparing with the `==` 
operator because two empty strings always compare equal with 
`==`, regardless of what they point to.

     string s = "hello";
     string empty1 = s[0 .. 0];
     string empty2 = s[1 .. 1];
     assert(empty1 == null);
     assert(empty2 == null);
     assert(empty1 == empty2);

The real problem is that `s == null` looks like it does one thing 
(test for a null pointer) while actually doing something slightly 
different (test for an empty string).


More information about the Digitalmars-d-learn mailing list