Duplicate
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++
?
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++
?
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.
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) { ... }
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.
This same question has already been answered on StackOverflow: Do you use NULL or 0 (zero) for pointers in C++?
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.