null == "" is true?

Antonio antonio at abrevia.net
Tue Jul 12 20:36:03 UTC 2022


On Tuesday, 12 July 2022 at 18:56:43 UTC, Paul Backus wrote:
> 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).


Then:

```d
string a = null;
assert(a is null);
assert(a == "");

string b = "");
assert(b !is null);
assert(b == "");

```

Honestly, it is difficult to understand for newcomers... there is 
a reason, but there is a reason in javascript for `0 == ''` too


More information about the Digitalmars-d-learn mailing list