Why 1 is error and 2 is legal.
This code is taken from C++ primer 5th edition, There is not much detail on this[Edit: This is not a duplicate question, The so-called original question is very generic]
const double pi = 3.14;
const double *cptr = π
*cptr = 42; // 1
double dval = 3.14;
cptr = &dval; // 2
cptr is a pointer to a constant double. Initially it points to the constant double pi. *cptr = 42; will try to change the value of pi. However since pi is a constant value, it can't be changed.
cptr = &dval; changes the value of cptr, namely it now contains the address of val. This is allowed since cptr is not a constant pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With