Can we use `const_cast` to change a constant variable?

int main() { const int ia = 10; int *pia = const_cast<int*>(&ia); *pia = 5; std::cout << &ia << "\t" << pia <<endl; std::cout << ia << "\t" << *pia <<endl; return 0; } 

Output:

 0x28fef4 0x28fef4 10 5 

*pia and ia have the same address, but have different meanings. My goal is to use const_cast to change the value of a constant, but as a result, it shows that it does not work.

Does anyone know why?

+6
source share
2 answers

This behavior is undefined to change a constant value. Do not do this. If you need to change a value, do not declare it as const .

+6
source

The reason you see 10 printed for ia is most likely a compiler optimization: it sees the const object, decides that it will not change, and replaces the last printout as follows:

 cout<< 10 <<" "<<*ppa<<endl; 

In other words, the generated code has a value of const , "baked in" binary format.

Discarding the constant of an object that was originally declared as const , and writing to this object is undefined behavior:

$ 5.2.11 / 7 - Note: depending on the type of object, a write operation through a pointer, lvalue, or a pointer to a data item obtained from const_cast, which discards const-qualifier68), can lead to undefined behavior (7.1.5.1).

Depending on the platform, const objects may be placed in a protected area of ​​memory that you cannot write to. Working with const -ness in a type system can help compile your program, but you can see random results or even crash.

+6
source

Source: https://habr.com/ru/post/955343/


All Articles