Hello!
Despite of the "const" in the variable declaration, why can't I change the value of "x" if did that casting to(int*)? The address of "x" and the content of "ptr" are the same.
If I remove that "const" of the declaration I can do what I want and the content of "x" and "ptr" are the same, as well as before removing "const". I don't understand!
I'm using g++ (GCC) 8.2.1 20181127.
I don't really want to do that I'm just studying and trying to understand.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
int main(int argc, charconst *argv[])
{
constint x = 90;
int* ptr = newint;
ptr = (int*)&x;
*ptr = 50;
std::cout << "The address of x is: " << &x << "\n";
std::cout << "The content of ptr is: " << ptr << "\n";
std::cout << "The value of x is: " << x << "\n";
return 0;
}
A program that modifies the value of an object declared const has undefined behavior. This is why your program's behavior makes no sense.
This snippet is fine:
1 2 3
int x = 90;
intconst* ptr = &x;
*const_cast<int*>(ptr) = 100;
Because the object being modified (x) is not declared const.
Very strongly prefer C++-style explicit casts (e.g., const_cast over C's casts).
Hopefully it's obvious that a stray const_cast<int*>(ptr) is more likely to draw careful scrutiny than a C-style cast, which does not make it clear that cv-qualifiers are being removed.
EvilTM or not, casting away const can be substantially useful (for example, to reduce code duplication or to interface with const-incorrect code), but it is best avoided.