I searched the Internet and the StackOverflow about the const_cast<> and the confusion it causes, I found useful things, however I still has a question.
Considering this code,
#include <iostream>
using namespace std;
int main(void)
{
const int a = 1;
int *p = const_cast<int*>(&a);
*p = 2;
cout << "value a="<< a << endl;
cout << "value *p=" <<*p << endl;
cout << "address a=" <<&a << endl;
cout << "address p=" <<p << endl;
}
The output is:
value a=1
value *p=2
address a=0x69fef8
address p=0x69fef8
I found that such code may result in undefined behavior. (for example the compiler may replace all the a
's with 1
's to optimize, and hence the cast has no meaning)
I also found this quote:
If you cast away the constness of an object that has been explicitly declared as const, and attempt to modify it, the results are undefined.
However, if you cast away the constness of an object that has not been explicitly declared as const, you can modify it safely.
and this:
Note that C++ provides
const_cast
to remove or add constness to a variable. But, while removing constness it should be used to remove constness off a reference/pointer to something that was not originally constant.
Now, considering the following modification on the code above:
int b = 1;
const int a = b;
the output is:
value a=2
value *p=2
address a=0x69fef4
address p=0x69fef4
I understand that:
a
in int a = 1
is a constant expression that is processed at compile-time.
a
in int a = b
is not and it can only be processed at run-time.
as described here.
My questions:
When is the const declaration explicit, and when is it not? and how could it be originally non-const?