LearnFrenzy
Sign in Take a free test

Control Instructions · Find the Error · Question 3

Error: a variable used as a case label Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

The program below has a bug. Which statement correctly describes it?

main.c
#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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links