Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Conversion from const int* to int* working with unexpected results [duplicate]

In c++, we know that we can't convert const int* into int*. But I have a code snippet where I am able to convert const int* into int*. I am a beginner in c++, i googled for this but i just got the links mentioning const int* can't be converted into int* to avoid const violation. I am not able to figure out why is it compiling 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;
 }

Also, the problem is the output of the above program is:

0x7fff5476db8c 0x7fff5476db8c
43 40

Can someone please explain c1 integer pointer is pointing to the same address for a1 but having different values 43 and 40 respectively.

like image 980
Mukesh Avatar asked Jan 06 '23 20:01

Mukesh


2 Answers

In C++, an object is const or it isn't. If it is const than any attempt to modify it will invoke undefined behaviour. That's what you did. At that point anything can happen. If you're lucky, it crashes. If you're less lucky, it works fine until your code is in the hand of a customer where it causes the greatest possible damage.

You can easily convert a const int* to an int* in C++. You just did. However, "const int*" and "int*" don't mean that the thing pointed to is const or not. It just means that the compiler won't let you assign in one case, and will let you assign in the other case. *c1 is const. Casting the pointer to int* doesn't change the fact that it is const. Undefined behaviour.

like image 56
gnasher729 Avatar answered Jan 08 '23 10:01

gnasher729


It's undefined behaviour.

But, in this case what's happened is that the compiler has realised that it can replace a1 in cout statement with the actual value 40, because it's meant to be const.

Never, ever rely on this though. It could just have easily tattoed your cat.

like image 25
Roddy Avatar answered Jan 08 '23 10:01

Roddy