When I took the test, I encountered a question about const, which is roughly as follows:
The following code is provided to check whether the code can be compiled, run, and run.
[Cpp]
Const int a = 1;
Int * B = (int *) &;
* B = 31;
The above code can be compiled and run successfully. After running, the value of a B is 31.
The key to this question is the const implementation mechanism in C language. In C, the variable modified by const cannot be modified. After disassembly, the variable modified by const has the same result as the variable without const modification. However, if you modify the const variable in the program, an error will be reported during compilation, for example:
[Cpp]
Const int a = 1;
A = 2;
When this code is compiled, an error is reported, namely error C2166: l-value specifies const object.
So how does C implement const. Www.2cto.com
In the initial C standard, there is no const, but after C ++ is available, const is added to the C standard. In fact, C has not done too much processing on the const variable. After compilation, const and common variables are no different, but in the compilation process, the compiler checks whether there is any code in the code that modifies the const variable. If so, an error is reported to the user. After compilation, the const variable is the same as the common variable. Furthermore, if memset is used to modify the content of the const variable, there is no problem at all. It can be seen that the const modification is a compilation-level limitation and generally does not involve the running level. In C, const is used to explicitly identify variables or functions that cannot be modified, and this restriction is imposed at the compilation level.
Therefore, in the first question, a is a const variable, and the entire code segment does not modify a. Therefore, it can be compiled. After compilation, a is the same as a common variable, and B can be modified completely, therefore, the code can be compiled or run successfully.