Home > Backend Development > C++ > Why Does a Const Variable at the Same Memory Address Show Different Values in C ?

Why Does a Const Variable at the Same Memory Address Show Different Values in C ?

Barbara Streisand
Release: 2024-11-28 17:26:14
Original
833 people have browsed it

Why Does a Const Variable at the Same Memory Address Show Different Values in C  ?

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;
}
Copy after login

This code surprisingly outputs:

40 65
0xbfacbe8c 0xbfacbe8c
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template