An object is defined as const int c = 10; and const_cast is used to write through a pointer to it. What is the result?
Correct answer
B. Undefined behaviour, because modifying an object that is genuinely const is not allowed
15 views
B. Undefined behaviour, because modifying an object that is genuinely const is not allowed
15 views
const_cast may remove const from a reference or pointer, but writing through it is undefined behaviour when the referenced object was originally defined const, because the compiler may place it in read-only memory or fold the value into computations. The cast is legitimate only when the underlying object is non-const, for example an interface taking const that must call a legacy non-const function.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is B? Ask here and get an explanation.