Search code examples
c++c++11nullptr

Can I guarantee that the address of nullptr is always 0?


I know that NULL is always 0, but why does the following code print the message?

#include <iostream>

using namespace std;

int main() {
    int* ptr = nullptr;
    if (ptr == 0) {
        cout << "Does it always work?";
    }
    return 0;
}

Solution

  • Yes.

    A pointer initialised from nullptr is a null pointer.

    Comparing a null pointer to the literal 0 (or to a std::nullptr_t, which nullptr is; together these are null pointer constants) yields true, always.

    You can't do this with any old expression, though; even if integer i is 1, i-i is not a valid null pointer constant, despite evaluating to 0 at runtime. Your program will not compile if you try to do this. Only the literal 0 is a valid null pointer constant that can be compared to pointers.

    Also, that does not necessarily mean that it has all bits zero, though! Much like how converting a bool to int gives you zero or one, but the actual underlying bits of the bool can be whatever the implementation likes.

    Finally, note that your terminology is slightly off; per [support.types.nullptr/1], nullptr itself has no address that can be taken