Is NULL guaranteed to be 0?

前端 未结 2 825
清歌不尽
清歌不尽 2021-01-05 04:54

I was wondering if NULL is guaranteed to be 0 in C++, so I searched and came across these:


This answer states that:

相关标签:
2条回答
  • 2021-01-05 05:08

    I think its fine practice to assume so. Having said that, it would be horrible practice to #undef NULL and or redefine it as something else. So long story short, it's not a 100% guarentee because it is possible to be something else, but it NEVER should be.

    0 讨论(0)
  • 2021-01-05 05:25

    Is NULL guaranteed to be 0?

    According to the standard, NULL is a null pointer constant (i.e. literal). Exactly which one, is implementation defined.

    Prior to C++11, null pointer constants were integral constants whose integral value is equal to 0, so 0 or 0l etc.

    Since C++11, there is a new null pointer literal nullptr and NULL may be defined as being nullptr. (And thus literal interpretation of Bjarne's quote has become obsolete).

    Prior to standardisation: NULL may be defined as (void*)0 in C. Since C++ was based on C, it is likely that some C++ dialects pre-dating the standard might have used that definition, but such definition is not conformant with standard C++.


    And for completeness: As explained in more detail in SO post linked in a comment below, null pointer constant being 0 does not necessarily mean that the value of the null pointer address is 0 (although the address being 0 is quite typical).

    What can be concluded about this:

    • Don't use NULL to represent the number zero (use 0 with appropriate type suffix if appropriate), nor to represent a null-terminator character (use '\0').
    • Don't assume that NULL resolves to a pointer overload.
    • To represent a null pointer, don't use NULL but instead use nullptr if your standard is >= C++11. In older standard you can use (T*)NULL or (T*)0 if you need it for overload resolution... that said there are probably very few cases where overloading integers with pointers makes any sense.
    • Consider that the definition may differ when converting from C to C++ and vice versa.
    • Don't memset (or type pun) zero bits into a pointer. That's not guaranteed to be the null pointer.
    0 讨论(0)
提交回复
热议问题