Machine-translated by Google. Questions are authored in English.
Top

Discussion

Which of the following errors would be reported by the compiler on compiling the program given below?

#include <stdio.h>
int main()
{
    int a = 5;
    switch(a)
    {
    case 1:
    printf("First");

    case 2:
    printf("Second");

    case 3 + 2:
    printf("Third");

    case 5:
    printf("Final");
    break;

    }
    return 0;
}

 

  • A.There is no break statement in each case.
  • B.Expression as in case 3 + 2 is not allowed.
  • C.Duplicate case case 5:
  • D.No error will be reported

Answer: C

Correct answer: Duplicate case case 5:

case 3 + 2 is perfectly legal - a label may be any constant expression, and the compiler evaluates it to 5. That is exactly the problem: it then collides with case 5, and duplicate labels are an error, since the jump would be ambiguous. Missing break statements are legal (they produce fall-through).

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.