Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a nullptr?

Tags:

c++

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?

like image 309
masoud Avatar asked May 13 '14 18:05

masoud


2 Answers

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 ]

like image 141
Michael Burr Avatar answered Oct 17 '22 05:10

Michael Burr


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.

like image 40
Jan Hudec Avatar answered Oct 17 '22 05:10

Jan Hudec