Is it safe to check a pointer to not being NULL
by writing simply if(pointer)
or do I have to use if(pointer != NULL)
?

- 32,406
- 45
- 166
- 297
-
14Truth is, if you're going to use an explicit check, it's just as effective -- and often preferred -- to test against `0` or `nullptr`. (`NULL` is a C'ism, and requires including a header file.) – cHao Jul 21 '13 at 12:04
-
@cHao Good to know. So we shouldn't use `NULL` at all in C++? – danijar Jul 21 '13 at 12:08
-
5@danijar You could use nullptr in modern C++. – SurvivalMachine Jul 21 '13 at 12:08
-
@danijar: Not unless you're aiming for compatibility with C. – cHao Jul 21 '13 at 12:10
-
9@cHao Where is the point in "aiming for compatibility with C"? – qdii Jul 21 '13 at 12:10
-
6@danijar: Yes, You shouldn't use `NULL` in C++ from hereon because `NULL` is implementation dependent macro which might gives you ambiguous behaviors. – Alok Save Jul 21 '13 at 12:13
-
2@qdii: Maybe you have C++ code that you are considering reusing in a C project, and you want to minimize the work required to port it later. It's not unheard of. – cHao Jul 21 '13 at 12:13
-
Actually its quite unlikely to share the code, its more likely to put a C interface on top of the C++ – paulm Jul 21 '13 at 17:23
-
3While this is not the 'if' case, see this ideone live demo as to why you should avoid "NULL" and "0" for pointers in C++: http://ideone.com/tbvXNs – kfsone Jul 21 '13 at 19:28
-
@cHao: If your C++ code can be ported back to C without a massive rewrite then you are writing horrible C++. OP, `if(ptr)` is fine. If anyone is confused as to what it means (i.e., not being explicit and testing against `nullptr`) then they don't know the first thing about the language they are using and should probably stay away from that code base for a while. – Ed S. Jul 23 '13 at 23:49
-
http://stackoverflow.com/questions/15950688/best-practices-how-to-check-for-null-return-value-in-c-c – Hal Canary Jul 24 '13 at 02:47
-
@cHao, sorry but I'm a little bit confused: between these two -- `if(pointer)` and `if(pointer != NULL)` or `if(pointer != nullptr)` -- which one is an explicit check? Also, which one did you mean is the preferred one: the first one `if(pointer)` or the second one `if(pointer != NULL)` / `if(pointer != nullptr)`? Thanks in advance! – Milan Feb 08 '21 at 20:50
-
1@Milan: An explicit check is `if (pointer != some_pointer)`, where in this case `some_pointer` is one of the several ways of generating a null pointer. Personally i prefer `if (pointer)`. I was just saying if you did want to explicitly compare it against something, `nullptr` is preferred, with `0` a close second and `NULL` a very distant third. – cHao Feb 18 '21 at 02:46
-
@cHao thank you so much for the clarification. I appreciate that. I understood that `if(pointer)` is as same as `if (pointer != nullptr)` and `if(pointer)` has better readability. But still, are there any other reasons, especially from the performance point of view, for preferring implicit check i.e. `if (pointer)` over explicit checks? – Milan Mar 01 '21 at 17:15
-
1@Milan: There's no real performance difference as long as the `0`, `nullptr`, or `NULL` is a constant expression. If you compare to another variable, the compiler is liable to generate a different, slower check for variable equality rather than a quick check for zeroness. But otherwise, the difference is entirely one of readability. – cHao Mar 01 '21 at 20:33
14 Answers
You can; the null pointer is implicitly converted into boolean false while non-null pointers are converted into true. From the C++11 standard, section on Boolean Conversions:
A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type
bool
. A zero value, null pointer value, or null member pointer value is converted tofalse
; any other value is converted totrue
. A prvalue of typestd::nullptr_t
can be converted to a prvalue of typebool
; the resulting value isfalse
.

- 108,737
- 14
- 143
- 193
Yes, you could.
- A null pointer is converted to false implicitly
- a non-null pointer is converted to true.
This is part of the C++ standard conversion, which falls in Boolean conversion clause:
§ 4.12 Boolean conversions
A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. A prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.

- 30,738
- 21
- 105
- 131

- 44,644
- 9
- 83
- 100
Yes, you can. In fact, I prefer to use if(pointer)
because it's simpler to read and write once you get used to it.
Also note that C++11 introduced nullptr
which is preferred over NULL
.

- 119,891
- 44
- 235
- 294
-
10A pointer isn't a boolean expression. It's converted implicitly. If it's better to read when you have to remember this conversion to understand is your opinion. It's just one kind of coding style. – harper Jul 21 '13 at 12:17
-
7@harper You can say it's a coding style. But you can apply the same logic to `if(som_integer)` vs `if(some_integer != 0)` because integers are also not booleans, right? I prefer to avoid `0` or `NULL` in an if-statement. – Yu Hao Jul 21 '13 at 12:33
-
13I would agree it's simply a matter of coding style. I have come to prefer `if (pointer)` myself, but `if (ptr != nullptr)` seems perfectly legitimate to me. On the other hand, if I saw someone on my team who wrote `if (some_integer)` I would make them change it to `if (some_integer != 0)`. However, I won't pretend that's not a relatively arbitrary preference on my part - I simply prefer not to treat pointers and integers the same. – Joel Jul 21 '13 at 13:48
-
Which of these make the most sense sense: `if (xyzzy)` vs. `if (xyzzy != nullptr)` vs. `if (xyzzy != 0)` vs. `if (xyzzy == 1)`? – franji1 Jul 21 '13 at 19:34
-
1@YuHao And since it's code style I would not state "it's preferred" but "I prefer". – harper Jul 22 '13 at 06:00
-
I used the term `xyzzy` on purpose. You can't tell if it's a pointer, an int, a real, a bool, or a 1 bit bit field (in that case then `if (xyzzy != 0)` has the same behavior as `if (xyzzy == 1)`). Hence, a little more context would be great. Regardless of what is "more efficient" or what "implicit conversion rules" exist, it would be great to know the type and semantics from **reading the code as-is**. Hence, I would utilize these 4 specific `if` expression forms for types bool, pointer, integer, and integer, respectively. – franji1 Jul 22 '13 at 12:56
-
5@franji1 Then how about `if(isReady)` `if(filePtr)` `if(serviceNo)`? Making bad variable names on purpose doesn't mean much in this case. Anyway I already got your point and understood it, but I can insist using my own coding style myself, OK? – Yu Hao Jul 22 '13 at 13:13
-
2@YuHao - I only meant to obfuscate the type on purpose to emphasize my point. I decided to generate an "answer" that better gets my point across. (Sadly, I tend to write code using both styles, but tend to prefer seeing the expanded version when doing maintenance, but tend to prefer the shorter version shen creating it). – franji1 Jul 22 '13 at 13:20
Question is answered, but I would like to add my points.
I will always prefer if(pointer)
instead of if(pointer != NULL)
and if(!pointer)
instead of if(pointer == NULL)
:
- It is simple, small
Less chances to write a buggy code, suppose if I misspelled equality check operator
==
with=
if(pointer == NULL)
can be misspelledif(pointer = NULL)
So I will avoid it, best is justif(pointer)
.
(I also suggested some Yoda condition in one answer, but that is diffrent matter)Similarly for
while (node != NULL && node->data == key)
, I will simply writewhile (node && node->data == key)
that is more obvious to me (shows that using short-circuit).- (may be stupid reason) Because NULL is a macro, if suppose some one redefine by mistake with other value.

- 1
- 1

- 57,103
- 20
- 141
- 208
-
8Using = instead of == almost always generates a compiler warning, in the days when it didn't people would use if ( NULL == ptr ) – paulm Jul 21 '13 at 17:25
-
2@paulm that I just added this point its called [Yoda Condition](http://en.wikipedia.org/wiki/Yoda_Conditions) some people don't like it as its less readable. – Grijesh Chauhan Jul 21 '13 at 17:26
-
3`(boolean expression)? true : false` is completely pointless. The expression evaluates either to `true` or to `false`; what you say is "if it's true, give me true, if it's false, give me false". In short: It's completely equivalent to the boolean expression itself. Note that `node == NULL` is a boolean expression. BTW, your two implementations return exactly the opposite of each other. Either you want `!=` in the first, or only one `!` in the second. – celtschk Jul 21 '13 at 18:26
-
BTW, one possible protection against `=` instead of `==` is to make your variables `const` whenever possible. For example, you could define your function as `isEmnpy(node* const head) { ... }`, and then the compiler would refuse to compile it if you accidentally wrote `node = NULL` instead of `node == NULL`. Of course that only works for variables which you really don't need to change. – celtschk Jul 21 '13 at 18:32
-
@celtschk you are correct I use this technique in C rather c++ I am more C programmer. BTW I read you comments again you have interesting point Thanks! – Grijesh Chauhan Jul 21 '13 at 18:35
-
Does C implicitly convert from int to enum? Because that would be needed for your second version after your edit (and you still have the mismatch between the two versions: The first returns `true` if `head` is `NULL`, while the second returns `false`) – celtschk Jul 21 '13 at 18:39
-
@celtschk `(node* const head)` will work for function not if/while. – Grijesh Chauhan Jul 21 '13 at 18:39
-
I don't understand what you mean. It makes the argument `head` const, and thus will not allow to assign to `head` anywhere in the function, including inside the `if` or `?:`. – celtschk Jul 21 '13 at 18:41
-
@celtschk for time being I have remove last point (my mistakes) thanks to correct me! I read again and if I can post some better thoughts I will update my answer Thanks a Lots Celtschk! – Grijesh Chauhan Jul 21 '13 at 18:44
-
I'd like to add that "if (smartptr == NULL)" won't work, and "if (smartptr.get() == NULL)" is bad, so the code is easier to maintain without "==" or "!=". Also, I personally often mix up the true/false or "=="/"!=" case in comparisons. – StellarVortex Jul 24 '13 at 07:49
-
@StellarVortex Thanks! but I didn't get it mean :( , why `if(smartptr == NULL)` won't works **?** because `smartptr` is object (not pointer) ? – Grijesh Chauhan Jul 24 '13 at 07:53
-
2Because the smart pointer classes have `T* get() const` instead of `operator T*() const` to avoid implicit conversions. They do however have an `operator bool() const`. – StellarVortex Jul 24 '13 at 08:03
-
@StellarVortex Stellar give me some time.. I will do it, and then let you know. – Grijesh Chauhan Jul 24 '13 at 08:17
Explicitly checking for NULL could provide a hint to the compiler on what you are trying to do, ergo leading to being less error-prone.

- 2,722
- 2
- 22
- 26
Yes, you can. The ability to compare values to zeros implicitly has been inherited from C, and is there in all versions of C++. You can also use if (!pointer)
to check pointers for NULL.

- 714,442
- 84
- 1,110
- 1,523
The relevant use cases for null pointers are
- Redirection to something like a deeper tree node, which may not exist or has not been linked yet. That's something you should always keep closely encapsulated in a dedicated class, so readability or conciseness isn't that much of an issue here.
Dynamic casts. Casting a base-class pointer to a particular derived-class one (something you should again try to avoid, but may at times find necessary) always succeeds, but results in a null pointer if the derived class doesn't match. One way to check this is
Derived* derived_ptr = dynamic_cast<Derived*>(base_ptr); if(derived_ptr != nullptr) { ... }
(or, preferrably,
auto derived_ptr = ...
). Now, this is bad, because it leaves the (possibly invalid, i.e. null) derived pointer outside of the safety-guardingif
block's scope. This isn't necessary, as C++ allows you to introduce boolean-convertable variables inside anif
-condition:if(auto derived_ptr = dynamic_cast<Derived*>(base_ptr)) { ... }
which is not only shorter and scope-safe, it's also much more clear in its intend: when you check for null in a separate if-condition, the reader wonders "ok, so
derived_ptr
must not be null here... well, why would it be null?" Whereas the one-line version says very plainly "if you can safely castbase_ptr
toDerived*
, then use it for...".The same works just as well for any other possible-failure operation that returns a pointer, though IMO you should generally avoid this: it's better to use something like
boost::optional
as the "container" for results of possibly failing operations, rather than pointers.
So, if the main use case for null pointers should always be written in a variation of the implicit-cast-style, I'd say it's good for consistency reasons to always use this style, i.e. I'd advocate for if(ptr)
over if(ptr!=nullptr)
.
I'm afraid I have to end with an advert: the if(auto bla = ...)
syntax is actually just a slightly cumbersome approximation to the real solution to such problems: pattern matching. Why would you first force some action (like casting a pointer) and then consider that there might be a failure... I mean, it's ridiculous, isn't it? It's like, you have some foodstuff and want to make soup. You hand it to your assistant with the task to extract the juice, if it happens to be a soft vegetable. You don't first look it at it. When you have a potato, you still give it to your assistant but they slap it back in your face with a failure note. Ah, imperative programming!
Much better: consider right away all the cases you might encounter. Then act accordingly. Haskell:
makeSoupOf :: Foodstuff -> Liquid
makeSoupOf p@(Potato{..}) = mash (boil p) <> water
makeSoupOf vegetable
| isSoft vegetable = squeeze vegetable <> salt
makeSoupOf stuff = boil (throwIn (water<>salt) stuff)
Haskell also has special tools for when there is really a serious possibility of failure (as well as for a whole bunch of other stuff): monads. But this isn't the place for explaining those.
⟨/advert⟩

- 117,950
- 5
- 174
- 319
-
1I can only see one sentence in this interminable screed that actually answers the question. – user207421 Jul 21 '13 at 22:18
-
@EJP: if you take the question literally ("_can_ I use"), then it's not answered explicitly at all (the answer is simply "yes"). I tried to give proper reasons for why the OP _should_ in fact use `if(ptr)` rather than `if(ptr != nullptr)`, to which there is quite a bit more to say. – leftaroundabout Jul 22 '13 at 01:52
Yes, Both are functionally the same thing. But in C++ you should switch to nullptr in the place of NULL;

- 131
- 1
- 13
Yes. In fact you should. If you're wondering if it creates a segmentation fault, it doesn't.

- 30,738
- 21
- 105
- 131

- 396
- 4
- 12
yes, of course! in fact, writing if(pointer) is a more convenient way of writing rather than if(pointer != NULL) because: 1. it is easy to debug 2. easy to understand 3. if accidently, the value of NULL is defined, then also the code will not crash

- 319
- 4
- 11
As others already answered well, they both are interchangeable.
Nonetheless, it's worth mentioning that there could be a case where you may want to use the explicit statement, i.e. pointer != NULL
.
Yes, you can always do this as 'IF' condition evaluates only when the condition inside it goes true. C does not have a boolean return type and thus returns a non-zero value when the condition is true while returns 0 whenever the condition in 'IF' turns out to be false. The non zero value returned by default is 1. Thus, both ways of writing the code are correct while I will always prefer the second one.

- 59
- 6
-
1The non-zero value by default is undefined if I remember correctly. – user207421 Jul 21 '13 at 22:19
I think as a rule of thumb, if your if-expression can be re-written as
const bool local_predicate = *if-expression*;
if (local_predicate) ...
such that it causes NO WARNINGS, then THAT should be the preferred style for the if-expression. (I know I get warnings when I assign an old C BOOL
(#define BOOL int
) to a C++ bool
, let alone pointers.)

- 3,088
- 2
- 23
- 43
"Is it safe..?" is a question about the language standard and the generated code.
"Is is a good practice?" is a question about how well the statement is understood by any arbitrary human reader of the statement. If you are asking this question, it suggests that the "safe" version is less clear to future readers and writers.

- 2,145
- 2
- 21
- 29
-
My intention was to ask if it is safe. Thefore I used that wording. However, what you wrote here is not an answer to the question. Instead, it should be a comment under the question. You can delete the answer and add a comment under the question then. – danijar Jul 24 '13 at 11:29
-
@danijar Don't you remember when you was new to StackOverflow and searched for the 'Comment' section without success? Someone with 7 reputation can't do that. – Broxzier Jul 24 '13 at 13:20
-
@JimBalter Which is very confusing, since you can see others do so. When I was new to SO someone blamed me for doing that. – Broxzier Aug 26 '13 at 09:09
-
@JimBalter I am not murdering and stealing. I was telling _danijar_ that _Fred Mitchell_ was a new user and could not post comments. – Broxzier Aug 26 '13 at 09:14
-
@JimBalter Which you started today. Also you are the one not understanding instead. That comment is only supporting the confusing of this. – Broxzier Aug 26 '13 at 09:47
-
@danijar - Sorry, yes, my "answer" was not an answer to your question. Your wording was fine. My (bad) answer was a response to the other answers that delved into the "good practice" domain - which is relevant to a question that you did not ask, but was implicitly raised by others. – Fred Mitchell Sep 05 '13 at 02:05