Search code examples
pointersdcomparison-operators

Use and implementation of the binary `is` operator with simple types in D. (DLang)


In D, is there any difference between the binary is operator in the case

void * p;
if ( p is null ) { }       // #1

using pointers, versus simply either

if  ( ! p ) { }            // #2a

or

if ( p == null ) { }       // #2b

without the is operator? (DLang)

(I'm restricting this to simple scalar types, no aggregates or complex types. I am aware that with classes is simply compares their addresses, iirc.)


Solution

  • With type void*, like other plain pointers, there's no difference. There's also no difference with int, but there are differences with other types, including float, arrays (including strings), structs, and classes.

    I suggest you always write what you mean with any type, so if you change the type later it will be ok. Use is for seeing if two references are the same. Use == for seeing if contents are the same. Avoid !p, unless perhaps p is known to be a plain bool type, since it has the most surprising behavior (it does cast(bool) which can call an overloaded opCast!bool on structs and classes, and does .ptr !is null on arrays, which opens the joy of null vs zero length arrays). Better to just say what you mean and keep the code explicitly readable and resilient against refactorings.