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?

3

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

10 Comments

One could redefine ==, too, so it's unclear which is better. Though if you are daft enough to define a==0 != !a, you deserve all that comes to you...
IIRC, segmented x86 has null pointers that aren't necessarily all-bits-zero (due to use of segment registers), and the compiler must make sure that they compare equal to 0 . There's probably some x86 around today (notably in devices such as cameras and other embedded controllers).
I thought of that, but I won't call 16 bits segmented x86 in wide use today.
The compiler would compile both equivalently. I don't know what you mean by NULL always zero.
@PintoDoido: today, a camera is a programmable, embedded, computer system.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.