Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we use `const_cast` to modify a constant variable? [duplicate]

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;
}

The output is:

0x28fef4       0x28fef4
10             5

*pia and ia have the same address, but they have different values. My purpose is to use const_cast to modify a constant value, but as the result shows that it does not work.

Does anyone know why?

like image 805
micx Avatar asked Oct 06 '13 11:10

micx


People also ask

Can a const variable be modified?

Constants are block-scoped, much like variables declared using the let keyword. The value of a constant can't be changed through reassignment (i.e. by using the assignment operator), and it can't be redeclared (i.e. through a variable declaration).

Can you modify the constant variable in C++?

In C or C++, we can use the constant variables. The constant variable values cannot be changed after its initialization.

What is const_cast used for?

const_cast is one of the type casting operators. It is used to change the constant value of any object or we can say it is used to remove the constant nature of any object. const_cast can be used in programs that have any object with some constant value which need to be changed occasionally at some point.

Can we alter and existing constant?

Overview. A constant is a value that cannot be altered by the program during normal execution, i.e., the value is constant.


1 Answers

The reason why you see 10 printed for ia is most likely the compiler optimization: it sees a const object, decides that it's not going to change, and replaces the last printout with this:

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

In other words, the generated code has the value of the const "baked into" the binary.

Casting away the const-ness of an object that has originally been declared as const and writing to that object is undefined behavior:

$5.2.11/7 - Note: Depending on the type of the object, a write operation through the pointer, lvalue or pointer to data member resulting from a const_cast that casts away a const-qualifier68) may produce undefined behavior (7.1.5.1).

Depending on the platform, const objects may be placed in a protected region of memory, to which you cannot write. Working around the const-ness in the type system may help your program compile, but you may see random results or even crashes.

like image 123
Sergey Kalinichenko Avatar answered Sep 23 '22 20:09

Sergey Kalinichenko