Variable at Same Address Producing Divergent Values
Consider the following code snippet:
#include <iostream> using namespace std; int main(void) { const int a1 = 40; const int* b1 = &a1; char* c1 = (char *)(b1); *c1 = 'A'; int *t = (int*)c1; cout << a1 << " " << *t << endl; cout << &a1 << " " << t << endl; return 0; }
This code surprisingly outputs:
40 65 0xbfacbe8c 0xbfacbe8c
How is it possible that the variable a1 at the same address produces two distinct values, 40 and 65?
Answer:
This behavior is the result of undefined behavior. The code modifies the value of a const variable (a1), violating the rules of C . According to the C standard (section 7.1.6.1 paragraph 4), any attempt to modify a const object during its lifetime results in undefined behavior.
In this case, modifying the const variable a1 through the pointer c1 leads to unpredictable results. The compiler may ignore the modification, behavior in a documented manner, or even terminate the program.
Therefore, the observed behavior, where a1 produces two different values, is a consequence of undefined behavior. Modifying const variables is strongly discouraged and may lead to unpredictable and erroneous program behavior.
The above is the detailed content of Why Does a Const Variable at the Same Memory Address Show Different Values in C ?. For more information, please follow other related articles on the PHP Chinese website!