When testing for NULL, I see a lot of code that uses !var. Is there a reason to use this kind of test as opposed to the more explicit var == NULL. Likewise would if (var) be a correct test for an item being non-null?
When testing for NULL , I see a lot of code that uses !var
Share
The difference between:
!varand
var == NULLis in the second case the compiler have to issue a diagnostic if
varis not of a pointer type andNULLis defined with a cast (like(void *) 0).Also (as pointed by @bitmask in the comments) to use the
NULLmacro, you need to include a standard header that defines theNULLmacro. In C theNULLmacro is defined in several headers for convenience (likestddef.h,stdio.h,stdlib.h,string.h, etc.).Otherwise the two expressions are equivalent and it is just a matter of taste. Use the one you feel more confortable at.
And for your second question
if (var)is the same asif (var != NULL)with the difference noted above.