Reputation: 151
what is the difference between
const int d=1;
const int *p = &d;
and
const int d=1;
int const *p = &d;
What can I do with the former and the latter ?
Upvotes: 0
Views: 72
Reputation: 111
const int *p;
p
is a pointer to a constant integer. You can change the value stored in p
(thus it point somewhere else) but you can't change the value where p
points to.
int* const p;
p
is a constant pointer to a non constant integer. You can't change the value of p
, but change the integer where it points to
Upvotes: 0
Reputation: 55425
const int *p;
The declaration above declares a pointer p
that points to a constant int
. In other words, you can't change the value of the referand but you can change p
itself.
int* const p;
The declaration above declares a constant pointer p
that points to an int
. In other words, you can change the value of the referand, but you can't change p
. Also,
const int d = 1;
int * const p = &d;
is not legal. Taking the address of d
yields const int*
, and coversion from const int*
to int*
is not allowed (you could inadvertedly change the value of a constant object if it were).
You could make the conversion explicitly by using const_cast
:
const int d = 1;
int * const p = const_cast<int*>(&d);
but it would still be illegal (undefined behaviour) to change the value of d
through p
.
Upvotes: 0
Reputation: 477512
There is no difference, they're completely identical.
The grammar of the language simply allows a certain amount of freedom for certain constructions, and CV-qualification of types is one of those situations. There are other examples (e.g. declarations like foo typedef int;
).
Upvotes: 4