Unexpected result comparing to null
jfondren
julian.fondren at gmail.com
Mon Aug 23 13:10:51 UTC 2021
On Monday, 23 August 2021 at 13:00:36 UTC, DLearner wrote:
> Hi
>
> The code below compiles and runs producing 'Not null'.
>
> ```
> void main()
> {
> import std.stdio;
>
> int Var1;
> int* ptrVar;
>
> ptrVar = &Var1;
>
> if (ptrVar == null) {
> writeln("Null");
> } else {
> writeln("Not null");
> }
> }
> ```
>
> However, should it not fail to compile, as '==' used instead of
> 'is'?
>
> Best regards
Perhaps you're thinking of note 12 in
https://dlang.org/spec/expression.html#equality_expressions ?
Which ends:
"Comparing against null is invalid, as null has no contents. Use
the is and !is operators instead."
But also begins:
"**For class objects**, the == and != operators are intended to
compare the contents of the objects, however an appropriate
opEquals override must be defined for this to work. The default
opEquals provided by the root Object class is equivalent to the
is operator."
ptrVal is just an int*, and == against it implies no attempt look
for a opEquals.
Contrast:
```d
class S {
int* p;
this(int* p) {
this.p = p;
}
}
void main() {
import std.stdio;
int Var1;
auto ptrVar = new S(&Var1);
if (ptrVar == null) {
writeln("Null");
} else {
writeln("Not null");
}
}
```
Which fails to compile with
```
Error: use `is` instead of `==` when comparing with `null`
```
More information about the Digitalmars-d-learn
mailing list