Checking if a string is null

Max Samukha samukha at voliacable.com.removethis
Wed Jul 25 04:36:19 PDT 2007


On Wed, 25 Jul 2007 11:12:19 +0100, Regan Heath <regan at netmail.co.nz>
wrote:

>Max Samukha wrote:
>> Using '== null' and 'is null' with strings gives odd results (DMD
>> 1.019):
>> 
>> void main()
>> {
>> 	char[] s;
>> 
>> 	if (s is null) writefln("s is null");
>> 	if (s == null) writefln("s == null");		
>> }
>> 
>> Output:
>> s is null
>> s == null
>> 
>> ----
>> 
>> void main()
>> {
>> 	char[] s = "";
>> 
>> 	if (s is null) writefln("s is null");
>> 	if (s == null) writefln("s == null");		
>> }
>> 
>> Output:
>> s == null
>> 
>> ----
>> 
>> Can anybody explain why s == null is true in the second example?
>
>Not I, it's inconsistent IMO and it gets worse:
>
>import std.stdio;
>
>void main()
>{
>	foo(null);
>	foo("");	
>}
>
>void foo(string s)
>{
>	writefln(s.ptr, ", ", s.length);
>	if (s is null) writefln("s is null");
>	if (s == null) writefln("s == null");
>	if (s < null)  writefln("s <  null");
>	if (s > null)  writefln("s <  null");
>	if (s <= null) writefln("s <= null");
>	if (s >= null) writefln("s <  null");
>	writefln("");
>}
>
>Output:
>0000, 0
>s is null
>s == null
>s <= null
>s <  null
>
>415080, 0
>s == null
>s <= null
>s <  null
>
>So, "" is < and == null!?
>and <=,== but not >=!?
>

You didn't update all writefln's :)

>
>This all boils down to the empty vs null string debate where some people 
>want to be able to distinguish between them and some see no point.
>
>I'm in the 'distinguishable' camp.  I can see the merit.  At the very 
>least it should be consistent!
>
>Regan

Anyway, it feels like an undefined area in the language. Do the specs
say anything about how exactly arrays/strings/delegates should compare
to null? It seems to be more than comparing the pointer part of the
structs.


More information about the Digitalmars-d-learn mailing list