3

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

2 Answers2

4

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.

DSC
  • 1,153
  • 7
  • 21
0

Because cptr is a pointer to a double constant.

When doing *cptr = 42; you are trying to change the variable, which cptr points at, so you are trying to change the value of pi, which is a constant.

When you do cptr = &dval; you reassign the pointer to point at a completely new thing, which is fine, since cptr is not a const pointer.

ruohola
  • 21,987
  • 6
  • 62
  • 97