const to non-const type cast using -fpermissive

Viewed 40

The below code:

#include<iostream>

using namespace std;

int main(){
    const int x = 2;
    cout << "&x: " << &x << ", x: " << x << endl;

    int *a = &x;
    *a = 16;
    cout << "a: " << a << ", *a: " << *a << ", x: " << x << ", &x: " << &x << endl;

    int* p = a;
    cout << "p: " << p << ", *p: " << *p << ", x: " << x << ", &x: " << &x << endl;
    *p = 15;
    cout << "*p: " << *p << ", x: " << x << ", &x: " << &x << endl;

}

It produces below output on compiling with -fpermissive:

$ g++ const.cpp  -fpermissive
const.cpp: In function ‘int main()’:
const.cpp:8:15: warning: invalid conversion from ‘const int*’ to ‘int*’ [-fpermissive]
     int *a = &x;
               ^


$ ./a.out 

&x: 0x7ffeead2042c, x: 2
a: 0x7ffeead2042c, *a: 16, x: 2, &x: 0x7ffeead2042c
p: 0x7ffeead2042c, *p: 16, x: 2, &x: 0x7ffeead2042c
*p: 15, x: 2, &x: 0x7ffeead2042c

This seems completely un-intuitional. How can the same address have two different values? Both a and &x have same address. But *a and x have different values. How is that possible? PS: It works as expected when I don't use const in the declaration of x.

0 Answers
Related