What is the difference between the following two pointer definitions
int i = 0;
const int *p = &i;
constexpr int *cp = &i;
What is the difference between the following two pointer definitions
int i = 0;
const int *p = &i;
constexpr int *cp = &i;
const int *p = &i;
means:
p
is non-const: it can be reassigned to point to a different inti
cannot be modified through p
without use of a castconstexpr int *cp = &i;
means:
cp
is const
: it cannot be reassignedi
can be modified through p
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.