0

While I was coding a program in C, I came up a question that I could not figure out. I was checking if a condition is met in an if statement but was wondering if there is any difference between the following:

if(ptr != NULL)
or
if(ptr)

To me, I feel like both of those are correct but in the C world, the second one would be used more and in the Java world, the first one is used more. Is one more correct then the other?

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
James Carter
  • 387
  • 2
  • 6
  • 18

2 Answers2

3

In C, anything that evaluates to 0 (zero) is "false", and anything non-zero is "true".

Thus when ptr is NULL, those two if conditions end up working the same way:

if (ptr != NULL) = if (0 != 0) = if (0)

and:

if (ptr) = if (0)

You'll get people debating which is better, but you'll see both in code. The first is more clear because it's more explicit. The second is shorter. Both are technically correct and equivalent.

Nate Hekman
  • 6,507
  • 27
  • 30
  • NULL is not equal to 0 for all the time. there is some platform which NULL != 0 – MOHAMED Apr 29 '13 at 16:21
  • @MOHAMED - I've never heard of that. What platforms? – Nate Hekman Apr 29 '13 at 16:23
  • http://stackoverflow.com/questions/15616177/is-null-false-in-c-and-c-anything-more-than-0x0-0b0-0-0 and http://c-faq.com/null/machexamp.html – MOHAMED Apr 29 '13 at 16:26
  • Interesting. However, those links indicate that `NULL` evaluates to "an integer constant with the value 0", though the bitwise representation of such a value may not be 0x0 on some platforms. I believe my answer is still correct and helpful since I'm not discussing the bitwise representation of the `if` conditions. – Nate Hekman Apr 29 '13 at 16:32
  • yes exactelly. even if the NULL is not 0 but for theses platforms NULL is evaluated to 0 so your answer is valid. – MOHAMED Apr 29 '13 at 16:34
1

Both are correct and equivalent.

A pointer alone evaluates to false if the pointer is NULL and to true otherwise.

Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198