LearnFrenzy
Sign in Take a free test

Control Instructions · Find the Error · Question 7

Error (C17): declaration right after a case label Answer, explanation & discussion

  • Find the error
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

Compiled as C17, this program is rejected. Why?

main.c
#include <stdio.h>

int main(void) {
    int n = 1;
    switch (n) {
    case 1:
        int doubled = n * 2;
        printf("%d\n", doubled);
        break;
    default:
        puts("other");
    }
    return 0;
}
  • A doubled must be declared before main()
  • B Before C23 a label must be followed by a statement, and a declaration is not a statement; wrap the case in braces Correct
  • C printf cannot be used in a case
  • D There is no bug
Correct Answer: Option B

Write case 1: { int doubled = n * 2; … break; }. The braces also limit the variable's scope to that case. C23 lifted the rule, but the braces remain good style.

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