null == "" is true?

Hipreme msnmancini at hotmail.com
Tue Jul 12 17:02:57 UTC 2022


On Tuesday, 12 July 2022 at 16:40:38 UTC, H. S. Teoh wrote:
> On Tue, Jul 12, 2022 at 04:27:44PM +0000, Antonio via 
> Digitalmars-d-learn wrote:
>> It works
>> 
>> ```d
>> void main()
>> {
>>    assert(null=="");
>> }
>> ```
>> 
>> why?
>
> 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.
>
>
> T

Yup, always compare the string with "". I have had this kind of 
problem a bunch of times, comparing it with null but it is not 
actually null


More information about the Digitalmars-d-learn mailing list