is ==

Neia Neutuladh neia at ikeran.org
Sat May 19 17:13:36 UTC 2018


On Saturday, 19 May 2018 at 04:30:24 UTC, Jonathan M Davis wrote:
> On Saturday, May 19, 2018 03:32:53 Neia Neutuladh via 
> Digitalmars-d-learn wrote:
>> > Of course, the most notable case where using == with null is 
>> > a terrible idea is dynamic arrays, and that's the case where 
>> > the compiler _doesn't_ complain. Using == with null and 
>> > arrays is always unclear about the programmer's intent and 
>> > almost certainly wasn't what the programmer intended. If the 
>> > programmer cares about null, they should use is. If they 
>> > care about lengnth, then that's what they should check. 
>> > Checking null with == is just a huge code smell.
>>
>> I feel like the array == null version is more explicit about 
>> not allocating memory. However, I'm paranoid about whether 
>> that's going to check the pointer instead, so I mostly use 
>> array.length == 0 instead.
>
> I'm not sure what memory allocations you're worried about. 
> Neither "" nor [] allocates memory

"" is syntax for compile-time constants and shouldn't ever 
allocate.

[] is a specific case of [values...]; the general case allocates, 
but this one case does not.

null is not even a compile-time constant; it's a value baked into 
the language and is guaranteed not to allocate.

> but regardless, if you're looking to check whether arr.ptr is 
> null, then that's effectively what you get with
>
> arr is null

I don't think I've ever wanted to distinguish a zero-length slice 
of an array from a null array.

> Regardless, if you're checking for null, then is does the job, 
> and if what you care about is whether the array is empty, then 
> that's what
>
> arr.length == 0
>
> and
>
> arr.empty
>
> do.

As I already said, I use "array.length == 0". "array.empty" is 
part of that newfangled range business.


More information about the Digitalmars-d-learn mailing list