# Include <iostream>
# Include <string>
Using namespace STD;
Int main ()
{
Const int num = 1;
Int * P = const_cast <int *> (& num );
* P = 2;
Cout <num <Endl; // output 1
Cout <* P <Endl; // output 2
// But & num and P are the same. Why?
Cout <& num <Endl;
Cout <p <Endl;
}
Question added:
I want to emphasize why the pointer P and & num are the same, but * P is different from num. How can there be two different values for the same address?
Answer:
C ++ usually does not allocate storage space for const!
Instead, the definition is saved in the symbol table. In addition, it is initialized when you enter the symbol table. In this example, the value of the symbol num will always be 1.
The use of pointers (take the address) is to forcibly allocate space! However, the result is not the same as the previous Const. Although space is forcibly allocatedProgramThe const in the symbol table is still used.
C ++ is flexible enough!