I'm new to C++ and am trying the learn the concept of pointer. Could someone tell me why the C++ statement below is illegal? It seems to me to be legit but I have been told its illegal.
int null = 0, *p = null;
The C++ standard allows pointers to be assigned the value 0
as a constant.
However, the code:
int null = 0;
int *p = null;
does not set p
to the constant 0
, it sets it to the value of null
, which is an integer variable.
If we generalize a little bit, and put int null = 0;
on a line, and int *p = null;
in a completely different line, with some code in between. There is nothing saying that the code in between doesn't do null = 4;
- however, I don't think that is the main reason for not allowing this, but rather that it is easier to write a compiler that checks "is this the integer constant 0" than "is this named constant of the value zero". What if the constant is from another compile unit (a link-time constant)?
Also, reading 0
is much easier than having 46 different coding standards, each of which uses a different name for null
.
Note that even if you make const int null = 0;
, it is still not the constant 0
- it's a constant of the same value as 0
, but not the same, lexically, as 0
.