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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With