0

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?

tornikeo
  • 915
  • 5
  • 20
  • 1
    You're confusing "mutable-pointer to a const-value" and "const-pointer to a mutable-value". See the linked question. – Dai Aug 29 '20 at 11:00
  • The first example that says `// Not allowed!`, the comment is mistaken; it is allowed. – Eljay Aug 29 '20 at 11:51
  • @Eljay are you sure? It clearly says: error: assignment of read-only location ‘* ptr’ 15 | *ptr = 11; // Not allowed! | ~~~~~^~~~ – tornikeo Aug 29 '20 at 11:57
  • 1
    In the first example, `ptr = &other_int; // Not allowed!` – Eljay Aug 29 '20 at 11:58
  • Wow, *now* I'm curious. I didn't notice that. Why is that? O.o – tornikeo Aug 29 '20 at 12:01
  • I used the spiral rule and now it makes perfect sense. It's the data that is a constant not the pointer itself. I should have written `const int * const ptr` for that one. Thanks! – tornikeo Aug 29 '20 at 12:03
  • 1
    _What exactly does “const” guarantee?_ It means the programmer guarantees that the object marked `const` will not be modified in the context of the `const` and is thread-safe (either logically const or physically const). It does not mean the language guarantees it; the language has some checks to help enforce it. – Eljay Aug 29 '20 at 12:06

0 Answers0