Home > Software engineering >  Is it possible to change a const data value?
Is it possible to change a const data value?

Time:12-28

can someone explain to me why does this code doesnt change the value of a? is it possible to change a const data value?

case 1:

const int a = 2;
*((int*)&a) = 3;
std::cout << a;

case 2:

const int a = 2;
const_cast<int&>(a) = 3;
std::cout << a;

CodePudding user response:

Changing a const value is undefined behavior. I would advise you not to do it or write any program that does so.

CodePudding user response:

You aren't allowed to modify constant objects. casting to a non-const reference with const_cast is fine though, as long as you don't attempt to modify the value.

9.2.9.2 The cv-qualifiers (emphasis mine)

(4) Any attempt to modify ([expr.ass], [expr.post.incr], [expr.pre.incr]) a const object ([basic.type.qualifier]) during its lifetime ([basic.life]) results in undefined behavior.


Also both of your examples are basically the same - a c-style cast (cast notation) can be interpreted as following:

7.6.3 Explicit type conversion (cast notation)

(4) The conversions performed by
(4.1) a const_­cast ([expr.const.cast]),
(4.2) a static_­cast ([expr.static.cast]),
(4.3) a static_­cast followed by a const_­cast,
(4.4) a reinterpret_­cast ([expr.reinterpret.cast]), or
(4.5) a reinterpret_­cast followed by a const_­cast,
can be performed using the cast notation of explicit type conversion. The same semantic restrictions and behaviors apply, [...] .

In your case (4.1) applies, so the the c-style cast would be interpreted by your compiler as following:

const int a = 2;
*((int*)&a) = 3;

// ->

const int a = 2;
*const_cast<int*>(&a) = 3;

Basically the only time when you're allowed to cast away constness and modify the object is when you know for sure that the given object is itself not const, only the reference you have is.

e.g.:

void foo(int const& ref) {
    // we can cast away const here
    // because we know that a in main is NOT const.
    const_cast<int&>(ref) = 2;
}

int main() {
    int a = 1; // a is not const
    foo(a);

    printf("%d", a); // 2
}
  • Related