In C there is a condition: "if (a! = NULL)" is the same as the condition "if (a)"?

Let's say it ais a pointer, and after allocating memory for it, I want to check whether the memory was allocated successfully, I saw two ways to do this:

if(a != NULL)

if(a)

What is the difference between the first and second statements?

+6
source share
4 answers

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

They achieve the same goal. The only real difference in readability.


Their effect is the same, as they will lead to the same.

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

if(a != NULL)

is equivalent to:

if(a != 0)

which is very similar to:

if(a)

, a true.

, a , . , , NULL (, , 0).

+2

c faq:

(p) if (p!= 0)

, , () 0 . ; . .

+1

(a!= NULL) , (a). if false, 0 true. NULL 0, , a == 0, return false. .

, !

0

; , .

. , , , - /.

0

All Articles