Question 4
Back to Exercise
The program below has a bug. Which statement correctly describes it?
#include <stdio.h>
static const int LIMIT = 10;
int main(void) {
int *p = (int *) &LIMIT;
*p = 20;
printf("%d\n", LIMIT);
return 0;
}
- A The cast should be (const int *)
- B LIMIT was defined const and likely sits in read-only memory; writing through the cast pointer is undefined behaviour (here: a crash) Correct
- C static and const cannot be combined
- D There is no bug; it prints 20
Correct Answer: Option B
The cast only silences the compiler. The object itself is const, so the write is undefined – it crashes here, and elsewhere the compiler may print 10 because it folded the constant. If a value must change, do not make it const.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!