NULL vs nullptr

Is 0 == NULL in C?

In C, 0 == NULL is true because both are null pointer constants. Here is why the comparison works, what NULL expands to, and what to watch for.

On this page
  1. Yes, 0 == NULL is true in C
  2. What NULL expands to
  3. A short example
  4. The rule applies to the constant 0
  5. Checking for a null pointer
  6. Summary

Yes, 0 == NULL is true in C

In C, the expression 0 == NULL is true, so it evaluates to 1. Both sides are null pointer constants. The integer constant 0 is one, and NULL is one too.

The C standard defines a null pointer constant as an integer constant expression with the value 0, or that same expression cast to void *. A null pointer constant converts to a null pointer, and two null pointers compare equal. The result is true whichever definition NULL uses.

What NULL expands to

NULL is a macro from headers such as <stddef.h>, <stdio.h>, and <stdlib.h>. The C standard lets an implementation define it as any null pointer constant. Common definitions are 0 and ((void *)0). The header on your system shows which one is used.

A short example

#include <stddef.h>
#include <stdio.h>

int main(void) {
    if (0 == NULL) {
        printf("0 == NULL is true\n");
    }
    return 0;
}

A standard C compiler prints 0 == NULL is true.

The rule applies to the constant 0

The comparison is true because the literal 0 is a null pointer constant. A variable that happens to hold zero is not one. Compare these two cases:

int zero = 0;

if (zero == NULL) {
    /* Not a valid null pointer check when NULL is ((void *)0). */
}

Whether this compiles without a warning depends on how NULL is defined. If NULL is ((void *)0), many compilers warn, because an int variable is not a null pointer constant even when its value is 0.

Checking for a null pointer

For a pointer p, these checks are common:

if (p == NULL) { /* ... */ }
if (p == 0) { /* ... */ }
if (!p) { /* ... */ }

All three test the same thing. Most C code uses NULL because it makes the pointer check easy to read.

Readers who see both forms often ask, why use null instead of 0? The answer is mostly about clarity. NULL tells the reader that a pointer is involved, while 0 looks like a plain number.

Summary

In C, 0 == NULL is true. The constant 0 and NULL are both null pointer constants, so the comparison matches. Watch for the difference between the constant 0 and a variable that holds zero, because that difference decides whether the check is valid.

The complete guide to null vs nullptr

NULL vs nullptr in C++
Read the guide

Keep exploring

Guides from other topics

All topics →

SOLID Principles in C++

Learn the five SOLID principles in C++ with short examples of single responsibility, open/closed, Liskov, interface segregation and dependency inversion.