Const-modified constants cannot be directly modified, but can be indirectly modified through pointers.
In the following code, const-qualified a cannot be directly modified.
Void main () {const int a = 3; a = 1 ;}
In C ++Const-modified constants cannot be directly modified, but can be indirectly modified through pointers.
Let's look at the following example:
Output 5 3 after running
Run in one step and use the memory window for viewing. a is 3 before modification.
After a is indirectly modified using the pointer, a displays 5 in the memory.
The original intention is to modify the value of const constant a through the pointer, but after running, it is found that the output of a is still 3, and the value of a is not changed on the surface. But check the memory window and find that a has been changed. This is caused by Compiler Optimization. When a is met, the compiler reads 3 to a directly from the register rather than from the memory! To improve this situation, we can add a volatile modifier when defining a to avoid Compiler Optimization: