int 0 cast to a pointer =? null pointer?

Is a run-time integral value of 0, cast to a pointer, guaranteed to be a null pointer?
No, you only get that guarantee for a constant expression of value 0.
Really? I would have imagined it was. If not, how can this work?

1
2
char *ptr = new (std::nothrow) char[100];
if (!ptr) { cout << "Out of memory"; }


After all, I am comparing the pointer there to a value. It is the equivalent of if (ptr == 0). I can also write a function that returns a pointer, and I can return 0 to signify there's nothing to return, and the caller of my function would do the same exact comparison. So how come this cannot be guaranteed to be a null pointer?
After all, I am comparing the pointer there to a value.

Not exactly, you're converting it to bool, which yields false if ptr has a null pointer value and true otherwise.
In the explicit comparison, you're explicitly comparing it to the null pointer value. Since 0 is a constant expression, the conversion to the null pointer value is guaranteed here.

But it's not guaranteed in the following case:
1
2
ptrdiff_t n=0;
if (ptr==reinterpret_cast<char*>(n))...
I'm having a hard time believing that, Athar.

I fail to see how a zero constant would ever be cast to a nonzero constant, regardless of what the types are.

The only way I can see that happening would be if the compiler was doing pointer math behind the scenes (casting between parent/child pointer types in a class hierarchy), but that wouldn't be the case here.
The point is that the null pointer value can be something other than zero.
There are few systems where this is the case, although none of them matter in every-day software development.
http://c-faq.com/null/machexamp.html

However, the internal representation shouldn't matter anyway in a valid C++ program.
Last edited on
closed account (1vRz3TCk)
the standard wrote:

A value of integral type or enumeration type can be explicitly converted to a pointer.64) 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.
...
64)Converting an integral constant expression with value zero always yields a null pointer, but converting other expressions that happen to have value zero need not yield a null pointer.
page 75
Very interesting!
...really?
Topic archived. No new replies allowed.