When in C++ I declare a null pointer to be int* p=0
, does that mean the zero is some special constant of integer pointer type, or does it mean that p
Yes. Zero is a special constant. In fact, it's the only integral constant which can be used, without using explicit cast, in such statements:
int *pi = 0; //ok
char *pc = 0; //ok
void *pv = 0; //ok
A *pa = 0; //ok
All would compile fine.
However, if you use this instead:
int *pi = 1; //error
char *pc = 2; //error
void *pv = 3; //error
A *pa = 4; //error
All would give compilation error.
In C++11, you should use nullptr
, instead of 0
, when you mean null pointer.
The C++ standard defines that the integer constant 0 converts to a null pointer. This does not mean that null pointers point to address 0x0. It just means that the text '0' turns into a null pointer when converted to a pointer.
Of course, making null pointers have a representation other than 0x0
is rather complicated, so most compilers just let 0x0
be the null pointer address and make sure nothing is ever allocated at zero.
Note that using this zero-conversion is considered bad style. Use NULL
(which is a preprocessor macro defined as 0
, 0L
, or some other zero integral constant), or, if your compiler is new enough to support it, nullptr.