Checking if a string is null

Regan Heath regan at netmail.co.nz
Wed Jul 25 03:12:19 PDT 2007


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 >=!?


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


More information about the Digitalmars-d-learn mailing list