Empty string is null?

Mike Parker aldacron at gmail.com
Sun May 31 19:31:57 PDT 2009


hasen wrote:
> How to pass it to C functions that expect a non-null string? 
> Specifically to GTK+ (using gtkD)
> 
> I also asked this on stackoverflow 
> http://stackoverflow.com/questions/931360/
> 
>    ------------
> 
> Using D1 with phobos
> 
> I have a text entry field, instance of gtk.Entry.Entry,
> 
> calling setText("") raises a run time error
> 
>   Gtk-CRITICAL **: gtk_entry_set_text: assertion `text != NULL' failed
> 
> Why? It seems to be a problem with D, I tried this:
> 
>   string empty = "";
>   assert (empty != null);
>   my_entry.setText(empty)
> 
> The program terminated as the assertion failed.
> 
> How can I work around this?
> 

This is one of those D quirks that trip people up quite frequently. When 
testing a string for null using the regular ==/!= operators, an empty 
string will always result the same as a null string. To truly test for 
null, use the is/!is operators instead. This will not take the contents 
of the string into account. The following will do what you expect:

string empty = "";
assert(empty !is null);
my_entry.setText(empty);

And since strings, like all arrays, are structs with the length and ptr 
fields, you can also do either of the following:

assert(empty.ptr != null);
assert(empty.ptr !is null);


More information about the Digitalmars-d-learn mailing list