2

As far as i know, the NULL is actually not 0. So is there any difference in comparing a pointer with 0 or with NULL? Further what should be the correct usage. Thanks!

user9371102
  • 1,278
  • 3
  • 21
  • 43
Shash
  • 4,160
  • 8
  • 43
  • 67

3 Answers3

4

The correct usage is to use NULL : It's more readable (p == NULL -> you know that p is a pointer)

ted
  • 4,791
  • 5
  • 38
  • 84
nouney
  • 4,363
  • 19
  • 31
  • 6
    "Correct" is a bit strong here. It is more a matter of style. Even if NULL ifs not zero, it is guaranteed to evaluate as equivalent. – lnafziger Jul 08 '13 at 13:11
  • I see wrong descriptions here. It may happen that the NULL pointer's binary representation doesn't consist of all 0 bits, but even then, `NULL == 0`. – glglgl Jul 08 '13 at 13:36
4

In C,the macro NULL is defined as an implementation-defined null pointer constant, which in C99 can be portably expressed as the integer value 0 converted implicitly or explicitly to the type void*.
In C++ NULL is the integer literal for zero (0 or 0L) has been traditionally preferred to represent a null pointer constant.

Compiler would implicitly convert 0 to NULL in case of comparison with a pointer.

It is always safe to compare 0 with NULL.

banarun
  • 2,305
  • 2
  • 23
  • 40
  • 2
    "Most compilers would implicitly convert 0 to NULL in case of comparison with a pointer." Actually, this is required by the standard, so it should be "all compilers". – Dietrich Epp Jul 08 '13 at 18:27
  • 1
    @DietrichEpp and Inafzier Thanks. I updated the statement. – banarun Jul 09 '13 at 01:55
-1

NULL is not necessarily 0 and should only be used for pointers. NULL is a macro usually defined as (void*)0 but not always.

It's a pointer to no location in memory.

There's a very good new book called Understanding And Using C Pointers. Please read that one.

Don't use it for anything but pointers.

uchuugaka
  • 12,679
  • 6
  • 37
  • 55