6

Let's say a is a pointer, and after allocating memory for it, I want to check if the memory was allocated successfully, I've seen two ways doing this :

if(a != NULL)

if(a)

What is the difference between the first and second statements ?

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Idan
  • 61
  • 3

4 Answers4

2

is the condition : if(a != NULL) the same as the condition if(a)?

They achieve the same purpose. The only real difference is in readability.


Their effect is the same, since they will result in the same thing.

NULL is a macro that is almost always 0, so:

if(a != NULL)

is equivalent to:

if(a != 0)

which is pretty similar to:

if(a)

since it will check if the expression a evaluates to true.

So, if a is a pointer, they will be the same. If it's not, then it will depend on how NULL is defined (which as I said is almost always 0).

gsamaras
  • 71,951
  • 46
  • 188
  • 305
1

According to c faq :

if(p) is equivalent to if(p != 0)

and this is a comparison context, so the compiler can tell that the (implicit) 0 is actually a null pointer constant, and use the correct null pointer value. There is no trickery involved here; compilers do work this way, and generate identical code for both constructs. The internal representation of a null pointer does not matter.

Community
  • 1
  • 1
msc
  • 33,420
  • 29
  • 119
  • 214
0

(a != NULL) return a boolean which is the same thing for (a). An if statement return false if the content equals 0 and true otherwise. NULL means 0 so if a == 0 the if return false. So it's exactly the same thing for the compiler.

Hope it helps you !

cydef
  • 417
  • 3
  • 10
0

There's no functional difference; they are equivalent and they both test for null pointer.

Any preference is purely subjective. Just use one you like or the what's followed by your fellow programmers in your project/organization.

P.P
  • 117,907
  • 20
  • 175
  • 238