gargakshat98
gargakshat98

Reputation: 33

What is the difference between if( pointer == NULL) and if(!pointer)?

What is the difference in between using:

if( pointer == NULL) 

And

if(!pointer)

I am concerned with the differences between the two in respect to the following points:
1. Are they different for the compiler? If yes, then how?
2. Which of the two is the recommended coding style for general use and why?
3. Can you please explain how NULL is "seen" by the compiler.

Edit: For the sake of simplicity let pointer be of type int *.

Upvotes: 3

Views: 202

Answers (3)

eerorika
eerorika

Reputation: 238371

  1. Are they different for the compiler? If yes, then how?

If pointer indeed has a pointer type, then there is no difference at all for the compiler.

  1. Which of the two is the recommended coding style for general use and why?

There probably are recommendations either way.

A possible advantage of using !pointer is that there is no opportunity to mistype pointer = NULL, which has very different meaning, but is well-formed. Another advantage is that is requires less typing.

  1. Can you please explain how NULL is "seen" by the compiler.

As specified in the standard, NULL is an implementation defined macro, which expands to a null pointer constant.

Upvotes: 2

UKMonkey
UKMonkey

Reputation: 6993

  1. They are both a comparison to 0; one is just explicit. You can work out the difference to the compiler by looking at the assembly produced.

  2. This is a matter of opinion and therefore off topic.

  3. NULL is a macro that should equate to 0. For this reason it's considered bad practice to use when comparing to pointers since the nullptr has an implicit conversion to pointer types, thus preventing it being used with integers; while NULL has no such conversion and thus can be compared to integers.

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234715

Assuming pointer is a pointer type, if (pointer == NULL) is anachronistic and poor C++ since the the null pointer value in C++ is nullptr in C++ with type nullptr_t.

if (!pointer) is the much preferred idiom.

Upvotes: 5

Related Questions