Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Pointer to const [duplicate]

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
like image 492
Peter Walker Avatar asked Jul 31 '26 10:07

Peter Walker


1 Answers

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.

like image 74
DSC Avatar answered Aug 01 '26 22:08

DSC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!