Checking if a string is null

Derek Parnell derek at psyc.ward
Wed Jul 25 17:53:48 PDT 2007


On Wed, 25 Jul 2007 19:01:57 +0200, Frits van Bommel wrote:

> Since null arrays have length 0, they *are* empty arrays :P.

Not in my world. I see that null arrays have no length. That is to say, the
do not have any length, which is different from saying they have a length
and that length is zero.
 

>> All that I would like changed is for the compare, in the case of length 
>> == 0, to check the data pointers, eg.
>> 
>>  > int opEquals(T)(T[] u, T[] v) {
>>  >     if (u.length != v.length) return false;
>>       if (u.length == 0) return (u.ptr == v.ptr);
>>  >     for (size_t i = 0; i < u.length; i++) {
>>  >         if (u[i] != v[i]) return false;
>>  >     }
>>  >     return true;
>>  > }
>> 
>> This should mean "" == "" but not "" == null, likewise null == null but 
>> not null == "".
> 
> Let's look at this code:
> ---
> import std.stdio;
> 
> void main()
> {
>      char[][] strings = ["hello world!", "", null];
> 
>      foreach (str; strings) {
>          auto str2 = str.dup;
>          if (str == str2)
>              writefln(`"%s" == "%s" (%s, %s)`, str, str2, str.ptr, 
> str2.ptr);
>          else
>              writefln(`"%s" != "%s" (%s, %s)`, str, str2, str.ptr, 
> str2.ptr);
>      }
> }
> ---
> The output is currently (on my machine):
> =====
> "hello world!" == "hello world!" (805BE60, F7CFBFE0)
> "" == "" (805BE78, 0000)
> "" == "" (0000, 0000)
> =====
> Your change would change the second line (even if it actually allocated 
> a new empty string like you probably want instead of returning null). 
> How would that be consistent in any way?

Your example is misleading for at least two reasons:
** The '==' operator compares the contents of the strings. A null string
has no content so there is nothing to compare. This should fail but is
doesn't in the current D. It should fail in the same manner that a null
object reference fails the '==' operator.
** The output is 'writefln' attempt at given a string representation of the
data presented. It (aka Walter) has decided that the string representation
of a null array is an empty string. This does not mean that a null array is
an empty strng but just that writefln represents it as such.


-- 
Derek Parnell
Melbourne, Australia
"Down with mediocrity!"


More information about the Digitalmars-d-learn mailing list