What is the difference between the following two pointer definitions
int i = 0;
const int *p = &i;
constexpr int *cp = &i;
asked Feb 9, 2015 at 22:16
1 Answer 1
const int *p = &i;
means:
p
is non-const: it can be reassigned to point to a different inti
cannot be modified throughp
without use of a cast
constexpr int *cp = &i;
means:
cp
isconst
: it cannot be reassignedi
can be modified throughp
In both cases, p
is an address constant if and only if i
has static storage duration. However, adding constexpr
will cause a compilation error if applied to something that is not an address constant.
To put that another way: constexpr int *cp = &i;
and int *const cp = &i;
are very similar; the only difference is that the first one will fail to compile if cp
would not be an address constant.
answered Feb 9, 2015 at 23:56
Sign up to request clarification or add additional context in comments.
Comments
lang-cpp
constexpr *p
is a constant pointer to int and not a pointer to a const int