2

After const_cast, the value does not change in the main function. But changes when calling an external function, still prints the old value in the main (where const int is initialized first).

int main() {
    const int i = 5;
    int* p = const_cast<int*>(&i);
    *p = 22;
    std::cout<<i;
    return 0;
}

Output is 5, why? The watch-window shows value of i = 22:

Watch-window value

So why does it print 5 ? The output differs if I call an external function:

void ChangeValue(const int i) {
    int* p = const_cast<int*>(&i);
    *p = 22;
    std::cout<<i; //Here the value changes to 22
}

int main() {
    const int i = 5;
    ChangeValue(i); //Value changes to 22 in the ChangeValue function
    std::cout<<i // It again prints 5.
}

Why is the value not changed even if the value changes after calling the ChangeValue function?

I get the same output on a Linux Platform. Could someone please add clarity to my confusion?

Jonny Henly
  • 4,023
  • 4
  • 26
  • 43

1 Answers1

6

Trying to modify a constant value leads to undefined behavior, just don't do it.

As for why it doesn't change, the compiler sees that it is a compile-time constant and may store it in a read-only segment. It could also be because the compiler know the value is constant, and is using the actual value in the generated code, instead of reading the variable.


For the second program, the variable i can't be stored in a read-only segment, it's stored on the stack like any other local variable. However, since you marked i as constant attempting to modify it is still undefined behavior.

The reason the main program prints the old value, is because you pass the variable by value meaning it gets copied into the local variable i in the ChangeValue function. If the variable wasn't a constant in the main or the ChangeValue function, the value of i in the main function would still not change.

If you change the ChangeValue function to take its argument by reference, you might get the same behavior as the first program.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 1
    *"may store it in a read-only segment"* - that would likely cause a SIGSEGV or similar; seeing "5" printed is more plausibly related to the compiler not updating its internal records of the value of `i` when encountering the attempted write (it's under no obligation to model impact of code with *undefined behaviour*), and, for `cout << i`, using the original unchanged record of the value to load the register or stack position expected by `<<(std::ostream&, int)`. – Tony Delroy May 16 '16 at 06:44