2

Sometimes I see programmers use:

void *ptr = <something>;
if (ptr == NULL)
    <do something>;

Instead of:

void *ptr = <something>;
if (!ptr)
    <do something>;

Is there anything that can go wrong with if (!ptr), or is it just a coding style preference?

Bite Bytes
  • 1,455
  • 8
  • 24

1 Answers1

5

In C, it is just a coding style preference.

Some people prefer if (NULL == ptr) with the argument that if the programmer made a typo (and mistyped the == as a single =) the compiler will complain. However, many compilers would emit a warning for if (ptr=NULL) (at least recent GCC do, when invoked as gcc -Wall -Wextra as you should).


In C++ (where you would use nullptr instead of NULL) there could be a difference, because one can redefine operator ! (e.g. on smart pointers). However, on raw plain pointers (like void*, or sometype* or SomeClass*), you cannot redefine operators like ! or !=.


BTW, some weird processors might have NULL pointers which are not an all zero-bits machine word (but the compiler should deal with this issue). I can't name any such processor in wide use today (however think of 1980s segmented 16 bits x86 as a counter example).

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547