0

The title says it all. How am I able to change the value of a constant? Also is that the same as when you change the value of an element at index X of a constant array?

    #include<iostream>
    int main(){
        const char* y = "original";
        auto *p = &y;
        *p = "modified";
        std::cout<<y<<"\n";
        //outputs modified
        system("pause");
        return 0;
    }
Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52

1 Answers1

5

Note that y is a non-const pointer (to const). You're not modifying the const part, i.e. the const char pointed by y, but y itself; this is valid. BTW modifying y through the pointer p is just same as

const char* y = "original";
y = "modified";  // this is well-formed

On the other hand,

*y = 'm';  // this is ill-formed

If you make y const, then you might get the diagnostic you expected.

const char* const y = "original";
y = "modified";  // ill-formed
*y = 'm';        // ill-formed
songyuanyao
  • 169,198
  • 16
  • 310
  • 405