I am a beginner in C++ and have truble understanding the following sniped:
#include <iostream>
int main()
{
const int i { 100 };
const int* ip = &i; // okay, because ip points to const value
*ip = 0; // error, because i is const
// error because ip1 and ip2 do not point to a const value
int* const ip1 = &i;
int* ip2 = &i;
int* iq { const_cast<int*>(&i) }; // okay, because it removes the const from i
*iq = 0; // now I can assign a new value to i, because it no longer has a const value
std::cout << i << ", " << *iq; // 100, 0
}
In the code I play around with const pointers a little bit. In the end I use const_cast
to assign a value to *iq
, which is pointing to i
. This works because the const_cast
removed the "constness" from i
. If I print i
and *iq
, the result will show that i
is still 100 and *iq
is 0. Why are i and *iq not the same? They both should refer to the same value in memory, shouldn't they?
EDIT:
The following code works as expected:
const volatile int i { 100 };
int* iq { const_cast<int*>(&i) };
*iq = 0;
std::cout << i << ", " << *iq; // 0, 0