Example:
int main()
{
int some_int = 10;
int other_int = 11;
const int * ptr = &some_int;
ptr = &other_int; // Not allowed!
}
The above is expected, but this:
int main()
{
int some_int = 10;
const int * ptr = &some_int;
// *ptr = 11; // Not allowed!
some_int = 11; // Allowed! Has same effect.
}
Why does const
care about what is written in the memory the ptr
points to?
C++ supports two notions of immutability:
• const: meaning roughly ‘‘I promise not to change this value.’’ This is used primarily to specify interfaces so that data can be passed to functions using pointers and references without fear of it being modified. The compiler enforces the promise made by const. The value of a const can be calculated at run time. ...
"the compiler enforces the promise", what exactly does it enforce? I can still freely manipulate the memory that's pointed at. Does compiler only truly enforce the pointer's value?