C ++ Convert from const int * to int *, working with unexpected results

In C ++, we know that we cannot convert const int * to int *. But I have a piece of code where I can convert const int * to int *. I am new to C ++, I googled for this, but I just got links mentioning that const int * cannot be converted to int * to avoid breaking const. I cannot understand why it compiles without errors.

#include <iostream>
using namespace std;

int main(void)
{
    const int a1 = 40;
    const int* b1 = &a1;
    int* c1 = (int *)(b1);
    *c1 = 43;
    cout<< c1<<" "<< &a1<<endl;
    cout<< *c1<<" "<< a1<<endl;
 }

In addition, the problem is that the output of the above program:

0x7fff5476db8c 0x7fff5476db8c
43 40

Can someone explain that c1 is an integer pointer pointing to the same address for a1, but having different values ​​of 43 and 40, respectively.

+4
source share
4

++ const, . const, undefined. , . . , . , , , .

const int * int * ++. . , "const int *" "int *" , . , . *c1 - const. int* , const. undefined.

+6

undefined.

, , a1 cout 40, const.

, , . .

+2

A const int , a1 40. &a1 - . , , 40 . , .

This is nothing but undefined behavior and may differ from the compiler. One compiler can display 43, another can always be displayed 40, and some others can generate code to cause a failure (write to read-only memory). Do not do that!

0
source

Run it, maybe it will help.

const int a1 = 40;
std::cout<<"__________ const int a1 = 40; ____________________________________"<<std::endl;
std::cout<<"a1: "<< a1<<std::endl;
std::cout <<"&a1 "<< &a1<<std::endl;
std::cout <<"*a1: INVALID"<<std::endl;

const int* b1 = &a1;
std::cout<<"__________ const int* b1 = &a1; ____________________________________"<<std::endl;
std::cout<<"b1: "<< b1<<std::endl;
std::cout <<"&b1 "<< &b1<<std::endl;
std::cout <<"*b1 "<< *b1<<std::endl;

int* c1 = (int *)(b1);
std::cout<<"__________ int* c1 = (int *)(b1); ____________________________________"<<std::endl;
std::cout<<"c1: "<< c1<<std::endl;
std::cout <<"&c1 "<< &c1<<std::endl;
std::cout <<"*c1 "<< *c1<<std::endl;

*c1 = 43;
std::cout<<"__________ *c1 = 43; ____________________________________"<<std::endl;
std::cout<<"c1: "<< c1<<std::endl;
std::cout <<"&c1 "<< &c1<<std::endl;
std::cout <<"*c1 "<< *c1<<std::endl;

std::cout<<"c1: "<< c1<<std::endl;
std::cout<<"*c1: "<< *c1<<" -----> *&a1: "<< *&a1<<" - a1: "<< a1<<std::endl;
std::cout<<"&c1: "<< &c1<<std::endl;
0
source

All Articles