tags:

views:

396

answers:

5

Duplicate

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

When dealing with NULL pointers one can do this

if(ptr != NULL){ ... }

or this

if(ptr != 0){ ... }

Are there reasons to prefer one over the other in C++?

+11  A: 

Use NULL because it indicates semantically what you mean.

Remember, the point of programming isn't to tell the computer what to do. The point is to tell other humans what you're telling the computer to do.

Jason Cohen
AMEN! Code is primarily meant to be *read* by other humans.
Dan
"The point is to tell other humans what you're telling the computer to do" -- lovely! but I prefer to use `0`, it's a well known C++ idiom and shouldn't confuse anyone!
hasen j
NULL is meaningful only if you came to C++ from a C background.
Ferruccio
+2  A: 

It doesn't matter strictly: either will work. So will:

if (ptr) { ... }

Checking explicitly for NULL demonstrates intent of the if and for that reason, I think it aides maintainability to check using:

if (ptr != NULL) { ... }

antik
Why was this downvoted? I see nothing wrong with it.
+2  A: 

if( ptr != NULL ) reads better than if(ptr != 0). So, while you may save 3 keystrokes with the latter, you will help your coworkers maintain their sanity while reading your code if you use the former.

Chris W. Rea
+3  A: 

This same question has already been answered on StackOverflow: Do you use NULL or 0 (zero) for pointers in C++?

X-Istence
+2  A: 

It doesnt much matter. Every professional programmer will know what ptr = 0 and if( !ptr ) means, and it is perfectly compliant with the Standard. So do what you will, but whatever you do, just do the same thing all the time.

John Dibling