How to Use If (Pointer) Instead of If (Pointer != Null)

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

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
.

difference between if(pointer) vs if(pointer != NULL) in c++, cpplint issue

No, if pointer is really a pointer type there is no difference, so everything here is a question of coding style. Coding style in turn depends on habits in different communities so there can't be a general recommendation.

I personally prefer the first because it is shorter and more to the point and avoids the use of the bogus macro NULL.

In C NULL can be very different things (integer or pointer) and in C++ its use is even deprecated nowadays. You should at least use nullptr, there.

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

There is no difference. What your professor prefers is called Yoda conditions also see "Yoda Conditions", "Pokémon Exception Handling" and other programming classics.

It is supposed to prevent the usage of assignment(=) by mistake over equality(==) in a comparison, but modern compilers should warn about this now, so this type of defensive programming should not be needed. For example:

if( pointer = NULL )

will assign NULL to pointer when what the programmer really meant was:

if( pointer == NULL )

it should have been a comparison, Oops. Make this an error using Yoda conditions you will (see it live), with a similar message to this:

error: expression is not assignable

As jrok points out using:

if (!pointer)

avoids this problem all together in this case.

Here is a concrete example of why with a modern compilers we don't need this technique anymore(see it live):

#include <iostream>

int main()
{
int *ptr1 = NULL ;

if( ptr1 = NULL )
{
std::cout << "It is NULL" << std::endl ;
}

}

Note all the warnings:

warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
if( ptr1 = NULL )
~~~~~^~~~~~

note: place parentheses around the assignment to silence this warning
if( ptr1 = NULL )
^
( )

use '==' to turn this assignment into an equality comparison
if( ptr1 = NULL )
^
==

which makes it pretty hard to miss the problem. It is worth noting that in C++ nullptr should be preferred over NULL, you can look at What are the advantages of using nullptr? for all the details.

Note, in C++ there is the unlikely case with operator overloading that there could be some contrived case where they are not the same.

Note, the -Wparentheses warning in some ways forces a style choice, you either need to give up potentially valid uses of assignment in places where the warning is generated, for example if you use -Werror or choose to parenthesize those cases, which some may find ugly as the comment below suggests. We can turn of the warning in gcc and clang using -Wno-parentheses but I would not recommend that choice since the warning in general will indicate a real bug.

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


  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.

Checking null pointer && pointer- member value in the same if statement


...is it allowed to check that a pointer is not null and (&&) to also check one of its members value in the same if statement?

It's perfectly valid, it is not UB, the expression is evaluated from left to right, if the left part of the expression evaluates to false the right part is not evaluated. This is usually called operator short circuit.

The rationale is that if the first part is false, there is no possibilty of the whole expression being true, false && false is false, false && true is also false.

...if I write it as 2 separate if to make it more readable, can I expect the compiler to optimize it into a single if?

In light of the above answer, you wouldn't need two ifs, I would argue that it will not make your code more readable, I prefer the way you have it right know, in any case this is only my opinion. About the compiler, I wouldn't think that there will be much difference either way, as sampled in this live demo.

What is the most efficient way to test if a pointer is null?

It makes no difference what so ever. It's purely a style issue what you prefer.

By the way, you should use nullptr rather than NULL if you use C++11 or later.

Check pointer's nullability: !pointer or pointer == nullptr?

Both are equivaluent because nullptr is guaranteed to be converted to false when converted to a boolean.

From N4296:

4.12 Boolean conversions

1 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. For direct-initialization (8.5), a prvalue of type
std::nullptr_t can be converted to a prvalue of type bool; the
resulting value is false.

Do you use NULL or 0 (zero) for pointers in C++?

Here's Stroustrup's take on this: C++ Style and Technique FAQ

In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days.

If you have to name the null pointer, call it nullptr; that's what it's called in C++11. Then, nullptr will be a keyword.

That said, don't sweat the small stuff.



Related Topics



Leave a reply



Submit