Question 3
Back to Exercise
The program below has a bug. Which statement correctly describes it?
#include <stdio.h>
int main(void) {
int limit = 10, n = 10;
switch (n) {
case limit: puts("at the limit"); break;
default: puts("below");
}
return 0;
}
- A n and limit must be unsigned
- B A case label must be a constant expression; limit is a variable Correct
- C default must come first
- D There is no bug
Correct Answer: Option B
The compiler must know every label's value at compile time. Use an if, or make the value a constant: #define LIMIT 10, an enum constant, or C23 constexpr int limit = 10;.
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!