After const_cast
, the value does not change in the main function. But changes when calling an external function, still prints the old value in the main (where const int
is initialized first).
int main() {
const int i = 5;
int* p = const_cast<int*>(&i);
*p = 22;
std::cout<<i;
return 0;
}
Output is 5
, why? The watch-window shows value of i = 22
:
So why does it print 5 ? The output differs if I call an external function:
void ChangeValue(const int i) {
int* p = const_cast<int*>(&i);
*p = 22;
std::cout<<i; //Here the value changes to 22
}
int main() {
const int i = 5;
ChangeValue(i); //Value changes to 22 in the ChangeValue function
std::cout<<i // It again prints 5.
}
Why is the value not changed even if the value changes after calling the ChangeValue
function?
I get the same output on a Linux Platform. Could someone please add clarity to my confusion?