Is NULL in C required/defined to be zero?

前端 未结 4 2034
无人共我
无人共我 2020-12-01 07:23

NULL appears to be zero in my GCC test programs, but wikipedia says that NULL is only required to point to unaddressable memory.

Do any compilers make

4条回答
  •  误落风尘
    2020-12-01 08:06

    From the language standard:

    6.3.2.3 Pointers
    ...
    3 An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant.55) If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.
    ...
    55) The macro NULL is defined in (and other headers) as a null pointer constant; see 7.17.

    Given that language, the macro NULL should evaluate to a zero-valued expression (either an undecorated literal 0, an expression like (void *) 0, or another macro or expression that ultimately evaluates to 0). The expressions ptr == NULL and !ptr should be equivalent. The second form tends to be more idiomatic C code.

    Note that the null pointer value doesn't have to be 0. The underlying implementation may use any value it wants to represent a null pointer. As far as your source code is concerned, however, a zero-valued pointer expression represents a null pointer.

提交回复
热议问题