Is this undefined behavior with const_cast? [duplicate]
Asked Answered
E

3

8

What is happening here?

const int a = 0;
const int *pa = &a;

int *p = const_cast<int*>(pa);
*p = 1;  // undefined behavior ??
cout << a << *p;  // ??

My compiler outputs 0 and 1, but address of 'a' and value of 'p' is the same, so I'm confused how is this possible.

Effluence answered 8/8, 2014 at 18:18 Comment(0)
O
17

Quote from cppreference:

Even though const_cast may remove constness or volatility from any pointer or reference, using the resulting pointer or reference to write to an object that was declared const or to access an object that was declared volatile invokes undefined behavior.

So yes, modifying constant variables is undefined behavior. The output you see is caused by the fact that you tell the compiler that the value of a will never change, so it can just put a literal 0 instead of the variable a in the cout line.

Oralle answered 8/8, 2014 at 18:19 Comment(0)
C
7

§7.1.6.1 [dcl.type.cv]/p4:

Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior.

Coxswain answered 8/8, 2014 at 18:22 Comment(0)
D
1

Attempting to write on a const value is undefined behavior, for example to allow the compiler to allocate const values into read only memory (usually in code segment) or inline their value into expressions at compile time, which is what happens in your case.

Debrahdebrecen answered 8/8, 2014 at 18:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.