Can I use if (pointer) instead of if (pointer != NULL)?

119,537

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 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 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 misspelled if(pointer = NULL) So I will avoid it, best is just if(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 write while (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.

enter image description here

Share:
119,537

Related videos on Youtube

danijar
Author by

danijar

Researcher aiming to build intelligent machines based on concepts of the human brain. Website · Twitter · Scholar · Github

Updated on September 11, 2020

Comments

  • danijar
    danijar over 3 years

    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)?

    • cHao
      cHao almost 11 years
      Truth 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.)
    • danijar
      danijar almost 11 years
      @cHao Good to know. So we shouldn't use NULL at all in C++?
    • Fil Karnicki
      Fil Karnicki almost 11 years
      @danijar You could use nullptr in modern C++.
    • cHao
      cHao almost 11 years
      @danijar: Not unless you're aiming for compatibility with C.
    • qdii
      qdii almost 11 years
      @cHao Where is the point in "aiming for compatibility with C"?
    • Alok Save
      Alok Save almost 11 years
      @danijar: Yes, You shouldn't use NULL in C++ from hereon because NULL is implementation dependent macro which might gives you ambiguous behaviors.
    • cHao
      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
      paulm almost 11 years
      Actually its quite unlikely to share the code, its more likely to put a C interface on top of the C++
    • kfsone
      kfsone almost 11 years
      While 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.
      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 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.
    • Hal Canary
      Hal Canary almost 11 years
    • Milan
      Milan about 3 years
      @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!
    • cHao
      cHao about 3 years
      @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.
    • Milan
      Milan about 3 years
      @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?
    • cHao
      cHao about 3 years
      @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.
  • harper
    harper almost 11 years
    A 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
    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) vs if(some_integer != 0) because integers are also not booleans, right? I prefer to avoid 0 or NULL in an if-statement.
  • Joel
    Joel almost 11 years
    I 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.
  • paulm
    paulm almost 11 years
    Using = instead of == almost always generates a compiler warning, in the days when it didn't people would use if ( NULL == ptr )
  • Grijesh Chauhan
    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
    celtschk almost 11 years
    (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
    celtschk almost 11 years
    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.
  • Grijesh Chauhan
    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
    celtschk almost 11 years
    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)
  • Grijesh Chauhan
    Grijesh Chauhan almost 11 years
    @celtschk (node* const head) will work for function not if/while.
  • celtschk
    celtschk almost 11 years
    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 ?:.
  • Grijesh Chauhan
    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
    franji1 almost 11 years
    Which of these make the most sense sense: if (xyzzy) vs. if (xyzzy != nullptr) vs. if (xyzzy != 0) vs. if (xyzzy == 1)?
  • user207421
    user207421 almost 11 years
    I can only see one sentence in this interminable screed that actually answers the question.
  • user207421
    user207421 almost 11 years
    The non-zero value by default is undefined if I remember correctly.
  • leftaroundabout
    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 than if(ptr != nullptr), to which there is quite a bit more to say.
  • harper
    harper almost 11 years
    @YuHao And since it's code style I would not state "it's preferred" but "I prefer".
  • franji1
    franji1 almost 11 years
    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.
  • Yu Hao
    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
    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
    StellarVortex almost 11 years
    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.
  • Grijesh Chauhan
    Grijesh Chauhan almost 11 years
    @StellarVortex Thanks! but I didn't get it mean :( , why if(smartptr == NULL) won't works ? because smartptr is object (not pointer) ?
  • StellarVortex
    StellarVortex almost 11 years
    Because 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.
  • Grijesh Chauhan
    Grijesh Chauhan almost 11 years
    @StellarVortex Stellar give me some time.. I will do it, and then let you know.
  • danijar
    danijar almost 11 years
    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.
  • Broxzier
    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
    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
    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
    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
    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.