How Undefined Behavior Explains Two Different Values for a Variable
Although it may seem paradoxical, it is possible for a variable at the same address to produce two distinct values. This phenomenon can be attributed to undefined behavior.
In the provided code snippet, a constant integer (a1) is defined, and a constant pointer (b1) is assigned its address. Subsequently, a char pointer (c1) is cast from b1. By modifying c1, the value of a1 is effectively changed, despite being declared as a constant. Casting c1 back to an integer pointer (t) reveals this altered value.
These actions constitute undefined behavior, as attempting to modify a const variable violates the C standard. As specified in section 7.1.6.1, such behavior may lead to unpredictable results, including seemingly impossible outcomes like the one observed.
The standard clearly warns against such actions:
Therefore, while the observed behavior may seem curious, it is not a compiler optimization but rather a symptom of undefined behavior arising from the attempt to modify a constant variable.
The above is the detailed content of How Can a Const Variable in C Have Two Different Values?. For more information, please follow other related articles on the PHP Chinese website!