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

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

    i could be stored in a protected area of memory for ptr to point to. Of course anything can be the case, which is why it's undefined - which basically means don't depend on any particular behaviour occurring if you do try to trigger undefined behaviour.

    For all you know it could cause your computer to go into cardiac arrest or start shooting out laser beams, but you never know because it's ... (w a i t _ f o r _ i t) ... undefined ;).

提交回复
热议问题