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

前端 未结 5 1210
我在风中等你
我在风中等你 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:38

    I hade same problem, I added volatile, now it's modifying:

    #include
    using namespace std;
    
    int main()
    {
      volatile const int a=5;
      int *p = const_cast(&a);
      *p=6;
      cout<<"a="<

    Output:

    a=6
    

    volatile tells compiler that the identifier can be modified (if not by this code then by some one else, so do not perform any optimization)

提交回复
热议问题