if we are writing a code in C++ or any other language and we use if else
statement there then what is the difference in if(!x)
and if(x==null)
.
I was working on a code and I came through these two statements in a single code so I was pretty curious to know the difference between the above mentioned two.
Asked
Active
Viewed 184 times
0

paolo
- 2,345
- 1
- 3
- 17
-
1`if (x == null)` is not C++ (unless you previously defined a variable `null`). Did you mean `if (x == nullptr)` ? – paolo Jun 28 '22 at 07:47
-
1There is no difference in terms of functionality. However the `if (!x)` is less readable, with `if (x==nullptr)` I already know that `x` is a pointer. Implicit conversions is a pain. – freakish Jun 28 '22 at 07:49
-
2The *"or any other language"* part makes this question too broad, see e.g. https://stackoverflow.com/questions/5791158/javascript-what-is-the-difference-between-if-x-and-if-x-null which has a different answer from the C++ ones. – Bob__ Jun 28 '22 at 07:53
-
1In C++, it depends on what `x` and `null` are as neither has a standard meaning (`NULL` is something distinct from `null`). If `x` is a numeric or pointer type (e.g. `int`, `aStruct *`) and `null` is a variable or constant with value zero (and of a type that can be compared with `x`) then `!x` and `x == null` are (typically) equivalent. If `x` is an instance of a `class` type then meanings of `!x` and `x == null` depend on what `operator` functions are defined for that type (and those functions, in combination, may or may not be defined in a way that makes `!x` and `x == null` equivalent). – Peter Jun 28 '22 at 08:30
-
If we're talking **C++**, and assuming `x` is a pointer, then `if (!x)` is commonly used idiomatic shorthand for `if (x == nullptr)`. Whereas, assuming `null` is undefined, `if (x==null)` won't compile. – Eljay Jun 28 '22 at 11:38
1 Answers
0
!x
will return true
for every falsy value (null
, false
). Where as x == null
, will only return true
, if x
is null
.
-
-
`x == nullptr` also requires `x` to be a pointer. It won't work if it's a boolean. – paolo Jun 28 '22 at 07:53
-
If you are "quoting" this [answer](https://stackoverflow.com/a/5791194/4944425), please note that it's about a different language (JavaScript). – Bob__ Jun 28 '22 at 07:57