Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C, is the condition : "if(a != NULL)" the same as the condition "if(a)"? [duplicate]

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 ?

like image 651
Idan Avatar asked Oct 19 '17 12:10

Idan


1 Answers

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

like image 77
gsamaras Avatar answered Sep 21 '22 17:09

gsamaras