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, but regardless, if you're looking to check whether arr.ptr is null, then that's effectively what you get with arr is null - though IIRC, it still checks length in that case. It's just that the type system guarantees that a null dynamic array has a length of 0. You'd have to do some pretty screwy @system casting to have a null dynamic array with a length other than 0. But you can always do arr.ptr is null 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. arr == null is just risking confusion, because there's no way to know if the programmer meant arr is null or arr.empty Regardless, it's absolutely guaranteed that arr == null is going to avoid checking the value of ptr just like arr == arr2 won't check ptr if length == 0. == only cares that both arrays have the same number of elements and that they're equal with ==. If length is 0, there's no need to check the elements to verify that, and if the lengths don't match, there's no need to check the elements. If you actually used enough screwed up casts to get two dynamic arrays whose ptr values were null, and they had different lengths, you still wouldn't get a crash. The _only_ way to get a segfault from using == with a null dynamic array is if you did enough screwy @system casts to have two dynamic arrays with the same non-zero length, and one of them had a null ptr. It wouldn't even crash if they were both null, because it's going to check the ptrs before comparing the elements. Regardless, in no real program do you have to worry about segfaulting with == and dynamic arrays, and you don't have to worry about == ever allocating. The closest that you'd get to that would be if you compared against a non-null array literal. e.g. arr == [1, 2, 3] and if the compiler is smart enough, not even that should allocate (though I don't remember if it's that smart at the moment). Ultimately, the question of is vs == comes down to clarity of the programmer's intent. - Jonathan M Davis