C++ Quiz78 of 173
Difficulty:
⬅️ Prev: 178Quiz ID: 179Next: 184 ➡️

According to the C++23 standard, what is the output of this program?

#include <iostream>

int main() {
    const int i = 0;
    int& r = const_cast<int&>(i);
    r = 1;
    std::cout << r;
}
Hint

We've casted away constness, but we're still attempting to modify i, which is const.

Reveal answer

The program is (or may be) undefined

Explanation

Modifying a const object results in undefined behavior. Casting away constness does not help.

§[dcl.type.cv]¶4 in the standard:

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.

But we're modifying r, not i, so §[expr.const.cast]¶4 is also relevant:

The result of a reference const_cast refers to the original object if the operand is a glvalue (...).

i is a glvalue, so the result of the const_cast refers to i.

⬅️ Prev: 178Quiz ID: 179Next: 184 ➡️