1

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

Community
  • 1
  • 1
Frank
  • 64,140
  • 93
  • 237
  • 324
  • This same question has already been answered on StackOverflow: [Do you use NULL or 0 (zero) for pointers in C++?](http://stackoverflow.com/questions/176989/do-you-use-null-or-0-zero-for-pointers-in-c) – X-Istence Mar 30 '09 at 02:18

4 Answers4

16

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
  • 81,399
  • 26
  • 107
  • 114
  • 1
    "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 Mar 30 '09 at 03:17
  • NULL is meaningful only if you came to C++ from a C background. – Ferruccio Mar 30 '09 at 03:44
  • One place NULL can get you trouble is when implementing templated code. 0 will work for values templated to be pointers, as well as other types; NULL, OTOH, can cause compile errors when the template is instantiated for non-pointers types. (I otherwise agree with making the code communicate your intent to the human reader though) – Jeremy Friesner Sep 27 '13 at 18:36
6

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

Ðаn
  • 10,934
  • 11
  • 59
  • 95
antik
  • 5,282
  • 1
  • 34
  • 47
3

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
  • 5,430
  • 41
  • 58
3

It doesn't 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.

ljs.dev
  • 4,449
  • 3
  • 47
  • 80
John Dibling
  • 99,718
  • 31
  • 186
  • 324