Is this a nullptr?

c++

Solution

From C++11 5.2.10/5 Reinterpret cast [expr.reinterpret.cast] (emphasis added):

A value of integral type or enumeration type can be explicitly converted to a pointer. A pointer converted to an integer of suffcient size (if any such exists on the implementation) and back to the same pointer type will have its original value; mappings between pointers and integers are otherwise implementation-defined.

A related bit from 5.2.10/4:

A value of type std::nullptr_t can be converted to an integral type; the conversion has the same meaning and validity as a conversion of (void*)0 to the integral type. [ Note: A reinterpret_cast cannot be used to convert a value of any type to the type std::nullptr_t. —end note ]

Problem

Reading this Q&A, I thought `p` shouldn't be a `nullptr` even if `x` is `0`. Have I understood it right? ``` int main() { int x = 0; std::cin >> x; // Enter `0` void *p = (void *)x; // or: void *p = reinterpret_cast<void*>(x); if (!p) std::cout << "p is nullptr" << std::endl; } ``` After entering `0` in the standard input, the message `p is nullptr` will be shown in my GCC. According to the link, it shouldn't evaluate to `nullptr`, but the result is not as my expectation. Is the code undefined behavior? or unspecified result? Why does it evaluate to `nullptr`?

Original source

Related problems