Should `!var` or `var == NULL` be used?

c, pointers

Solution

The difference between:

`!var`

and

`var == NULL`

is in the second case the compiler have to issue a diagnostic if `var` is not of a pointer type and `NULL` is defined with a cast (like `(void *) 0`).

Also (as pointed by @bitmask in the comments) to use the `NULL` macro, you need to include a standard header that defines the `NULL` macro. In C the `NULL` macro is defined in several headers for convenience (like `stddef.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 as `if (var != NULL)` with the difference noted above.

Problem

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?

Original source

Related problems