ProgrammingVery hardProduct company OA

What is the behavior?

What is the behavior?
const int x = 10;
int *p = (int*)&x;
*p = 20;
printf("%d", x);
  1. A. Guaranteed to print 20
  2. B. Guaranteed to print 10
  3. C. Compilation error: cast from const int* is not allowed
  4. D. Undefined behavior: modifying an object originally declared const through a non-const pointer

Correct answer: D. Undefined behavior: modifying an object originally declared const through a non-const pointer

Casting away const-ness and writing through the resulting pointer is undefined behavior specifically because x was declared const; the compiler may have placed it in read-only memory (causing a crash) or may have assumed its value never changes and optimized reads of x elsewhere to a compile-time constant 10, regardless of the write.

More C Programming questions

Exams that ask this topic