string <-> null/bool implicit conversion

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Fri Aug 21 07:23:45 PDT 2015


On Friday, 21 August 2015 at 11:43:11 UTC, Steven Schveighoffer 
wrote:
> On 8/21/15 7:34 AM, "Marc =?UTF-8?B?U2Now7x0eiI=?= 
> <schuetzm at gmx.net>" wrote:
>> On Thursday, 20 August 2015 at 19:41:44 UTC, Jonathan M Davis 
>> wrote:
>>> On Thursday, 20 August 2015 at 17:50:11 UTC, Steven 
>>> Schveighoffer wrote:
>>>> if(arr != null)
>>>
>>> Definitely don't do that. IMHO, "== null and "!= null" should 
>>> be
>>> illegal. If you really want to check for null, then you need 
>>> to use
>>> "is null" or "!is null", whereas if you want to check that an 
>>> array is
>>> empty, check its length or call empty. By using "== null" or 
>>> "!=
>>> null", you tend to give the false impression that you're 
>>> checking
>>> whether the object or array is null - which is not what you're
>>> actually doing.
>>
>> I disagree. `is null` is the one that should be illegal. `is` 
>> is
>> supposed to do a bitwise comparison, but `null` is usually 
>> just a
>> pointer/reference, while a slice consists of both a reference 
>> and a
>> length. Which of those are compared?
>
> Both. null in this context is actually an array (with null 
> pointer and zero length).
>
> null is technically a no-type placeholder (defaulting to void * 
> without context). In different contexts it means different 
> things.
>
> arr is null -> both pointer and length are 0
> arr == null -> arr contains the same elements that null 
> contains.
> arr.ptr == null -> arr contains a null pointer (length could 
> technically be non-zero).

For all intents and purposes

arr is null

is equivalent to

arr.ptr is null

ptr is a read-only property, so you can only set the ptr to null 
if you set the array to null by assigning it null explicitly or 
by assigning it an array which is null. "is null" is how you're 
supposed to check pointers and references for null - explicitly 
comparing a class object to null with == is actually illegal - 
and I see no reason that arrays should be any different.

Regardless, using "is null" actually checks for whether an array 
is null, whereas "== null" checks whether it's empty and doesn't 
care about the ptr value - which is _not_ what most programmers 
are going to expect when you compare something against null.

- Jonathan M Davis


More information about the Digitalmars-d mailing list