Getting the same value of the const variable even after changing it through const_cast

前端 未结 5 1207
我在风中等你
我在风中等你 2021-01-21 23:47

Consider the below code snippet:

int main()
{
    const int i=3;
    int *ptr;

    ptr=const_cast(&i);
    *ptr=5;

    cout<<\"i= \"<&         


        
5条回答
  •  后悔当初
    2021-01-22 00:40

    Is it any compiler optimization mechanism that compiler replaces the variable in the program with the value?

    Yes; that will be why you don't see the value changing. The behaviour of trying to modify a const object is left undefined in order to allow optimisations like that (as well as allowing the objects to be placed in unwritable memory).

提交回复
热议问题