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
?
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 ]
The ISO/IEC 14882:2011 §4.10/1 (and §4.11/1 for member pointers) only says that a _constant integer expression that integral constant expression prvalue of integer type that evaluates to zero is a null pointer constant.
For integer values , the only requirement is in §5.2.10/5, which says that:
A pointer converted to an integer of sufficient 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.
So it is also implementation defined whether integer value 0 converts to null pointer or not. In most implementations it does, because it is easier that way.
Let's try to answer your question:
It is possible that reinterpret_cast<void*>(x) != nullptr
if int x = 0
. But it is not mandated. Actually, reinterpret_cast<void*>(x) == nullptr
in most platforms but depending on either one is Undefined Behaviour.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.