Can I use if (pointer) instead of if (pointer != NULL)?
Solution 1
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
.
Solution 2
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.
Solution 3
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
.
Solution 4
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.
Solution 5
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.
Related videos on Youtube
danijar
Researcher aiming to build intelligent machines based on concepts of the human brain. Website · Twitter · Scholar · Github
Updated on September 11, 2020Comments
-
danijar over 3 years
Is it safe to check a pointer to not being
NULL
by writing simplyif(pointer)
or do I have to useif(pointer != NULL)
?-
cHao almost 11 yearsTruth is, if you're going to use an explicit check, it's just as effective -- and often preferred -- to test against
0
ornullptr
. (NULL
is a C'ism, and requires including a header file.) -
danijar almost 11 years@cHao Good to know. So we shouldn't use
NULL
at all in C++? -
Fil Karnicki almost 11 years@danijar You could use nullptr in modern C++.
-
cHao almost 11 years@danijar: Not unless you're aiming for compatibility with C.
-
qdii almost 11 years@cHao Where is the point in "aiming for compatibility with C"?
-
Alok Save almost 11 years@danijar: Yes, You shouldn't use
NULL
in C++ from hereon becauseNULL
is implementation dependent macro which might gives you ambiguous behaviors. -
cHao almost 11 years@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.
-
paulm almost 11 yearsActually its quite unlikely to share the code, its more likely to put a C interface on top of the C++
-
kfsone almost 11 yearsWhile this is not the 'if' case, see this ideone live demo as to why you should avoid "NULL" and "0" for pointers in C++: ideone.com/tbvXNs
-
Ed S. almost 11 years@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 againstnullptr
) 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. -
Hal Canary almost 11 years
-
Milan about 3 years@cHao, sorry but I'm a little bit confused: between these two --
if(pointer)
andif(pointer != NULL)
orif(pointer != nullptr)
-- which one is an explicit check? Also, which one did you mean is the preferred one: the first oneif(pointer)
or the second oneif(pointer != NULL)
/if(pointer != nullptr)
? Thanks in advance! -
cHao about 3 years@Milan: An explicit check is
if (pointer != some_pointer)
, where in this casesome_pointer
is one of the several ways of generating a null pointer. Personally i preferif (pointer)
. I was just saying if you did want to explicitly compare it against something,nullptr
is preferred, with0
a close second andNULL
a very distant third. -
Milan about 3 years@cHao thank you so much for the clarification. I appreciate that. I understood that
if(pointer)
is as same asif (pointer != nullptr)
andif(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? -
cHao about 3 years@Milan: There's no real performance difference as long as the
0
,nullptr
, orNULL
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.
-
-
harper almost 11 yearsA 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.
-
Yu Hao almost 11 years@harper You can say it's a coding style. But you can apply the same logic to
if(som_integer)
vsif(some_integer != 0)
because integers are also not booleans, right? I prefer to avoid0
orNULL
in an if-statement. -
Joel almost 11 yearsI would agree it's simply a matter of coding style. I have come to prefer
if (pointer)
myself, butif (ptr != nullptr)
seems perfectly legitimate to me. On the other hand, if I saw someone on my team who wroteif (some_integer)
I would make them change it toif (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. -
paulm almost 11 yearsUsing = instead of == almost always generates a compiler warning, in the days when it didn't people would use if ( NULL == ptr )
-
Grijesh Chauhan almost 11 years@paulm that I just added this point its called Yoda Condition some people don't like it as its less readable.
-
celtschk almost 11 years
(boolean expression)? true : false
is completely pointless. The expression evaluates either totrue
or tofalse
; 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 thatnode == 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 almost 11 yearsBTW, one possible protection against
=
instead of==
is to make your variablesconst
whenever possible. For example, you could define your function asisEmnpy(node* const head) { ... }
, and then the compiler would refuse to compile it if you accidentally wrotenode = NULL
instead ofnode == NULL
. Of course that only works for variables which you really don't need to change. -
Grijesh Chauhan almost 11 years@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!
-
celtschk almost 11 yearsDoes 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
ifhead
isNULL
, while the second returnsfalse
) -
Grijesh Chauhan almost 11 years@celtschk
(node* const head)
will work for function not if/while. -
celtschk almost 11 yearsI don't understand what you mean. It makes the argument
head
const, and thus will not allow to assign tohead
anywhere in the function, including inside theif
or?:
. -
Grijesh Chauhan almost 11 years@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!
-
franji1 almost 11 yearsWhich of these make the most sense sense:
if (xyzzy)
vs.if (xyzzy != nullptr)
vs.if (xyzzy != 0)
vs.if (xyzzy == 1)
? -
user207421 almost 11 yearsI can only see one sentence in this interminable screed that actually answers the question.
-
user207421 almost 11 yearsThe non-zero value by default is undefined if I remember correctly.
-
leftaroundabout almost 11 years@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 thanif(ptr != nullptr)
, to which there is quite a bit more to say. -
harper almost 11 years@YuHao And since it's code style I would not state "it's preferred" but "I prefer".
-
franji1 almost 11 yearsI 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 thenif (xyzzy != 0)
has the same behavior asif (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 specificif
expression forms for types bool, pointer, integer, and integer, respectively. -
Yu Hao almost 11 years@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? -
franji1 almost 11 years@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).
-
StellarVortex almost 11 yearsI'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.
-
Grijesh Chauhan almost 11 years@StellarVortex Thanks! but I didn't get it mean :( , why
if(smartptr == NULL)
won't works ? becausesmartptr
is object (not pointer) ? -
StellarVortex almost 11 yearsBecause the smart pointer classes have
T* get() const
instead ofoperator T*() const
to avoid implicit conversions. They do however have anoperator bool() const
. -
Grijesh Chauhan almost 11 years@StellarVortex Stellar give me some time.. I will do it, and then let you know.
-
danijar almost 11 yearsMy 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.
-
Broxzier almost 11 years@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 over 10 years@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 over 10 years@JimBalter I am not murdering and stealing. I was telling danijar that Fred Mitchell was a new user and could not post comments.
-
Broxzier over 10 years@JimBalter Which you started today. Also you are the one not understanding instead. That comment is only supporting the confusing of this.
-
Fred Mitchell over 10 years@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.