ProgrammingHardProduct-company placement · C++

What does the C++ standard say about this code?

What does the C++ standard say about this code?
const int x = 5;
int* p = const_cast<int*>(&x);
*p = 6;
  1. A. x becomes 6
  2. B. Compile-time error at the const_cast
  3. C. It throws std::bad_cast
  4. D. Undefined behaviour, because x was originally defined const

Correct answer: D. Undefined behaviour, because x was originally defined const

const_cast only removes const from the pointer type; writing through it is allowed only if the object itself was not defined const. Here it was, so the write is undefined (x may even be folded into a constant).

More OOP with C++ and Java questions

Exams that ask this topic