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

C++PointersIf StatementNullNull Pointer

C++ Problem Overview


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

C++ Solutions


Solution 1 - C++

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 - C++

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 - C++

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 - C++

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 - C++

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

Solution 6 - C++

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.

Solution 7 - C++

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-guarding if block's scope. This isn't necessary, as C++ allows you to introduce boolean-convertable variables inside an if-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 cast base_ptr to Derived*, 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⟩

Solution 8 - C++

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

Solution 9 - C++

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

Solution 10 - C++

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.

See also https://stackoverflow.com/a/60891279/2463963

Solution 11 - C++

Yes, Both are functionally the same thing. But in C++ you should switch to nullptr in the place of NULL;

Solution 12 - C++

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.

Solution 13 - C++

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

Solution 14 - C++

"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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondanijarView Question on Stackoverflow
Solution 1 - C++JoniView Answer on Stackoverflow
Solution 2 - C++billzView Answer on Stackoverflow
Solution 3 - C++Yu HaoView Answer on Stackoverflow
Solution 4 - C++Grijesh ChauhanView Answer on Stackoverflow
Solution 5 - C++Minqi PanView Answer on Stackoverflow
Solution 6 - C++Sergey KalinichenkoView Answer on Stackoverflow
Solution 7 - C++leftaroundaboutView Answer on Stackoverflow
Solution 8 - C++darshandzendView Answer on Stackoverflow
Solution 9 - C++Palak JainView Answer on Stackoverflow
Solution 10 - C++z3moonView Answer on Stackoverflow
Solution 11 - C++ASHUTOSH SINGHView Answer on Stackoverflow
Solution 12 - C++user2280507View Answer on Stackoverflow
Solution 13 - C++franji1View Answer on Stackoverflow
Solution 14 - C++Fred MitchellView Answer on Stackoverflow