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

Discussion

A typical “switch” body looks as follows:

switch (controlling_expression)
{
  case label1:
    /*label1 statements*/
    break;
  case label2:
    /*label1 statements*/
    break;
  default:
    /*Default statements*/
}

Which of the following statements about it is incorrect?

  • A.“switch” body may not have any “case” label at all and it would still compile.
  • B.“switch” body may not have the “default” label and it would still compile.
  • C.“switch” body may contain more than one “case” labels where the label value of these “case” is same and it would still compile. If “switch” controlling expression results in this “case” label value, the “case” which is placed first would be executed.
  • D.“switch” body may not have any “break” statement and it would still compile.

Answer: C

Correct answer: “switch” body may contain more than one “case” labels where the label value of these “case” is same and it would still compile. If “switch” controlling expression results in this “case” label value, the “case” which is placed first would be executed.

That statement is the incorrect one: duplicate case labels are a compile-time error. Each label must be a distinct constant, precisely so that the jump is unambiguous - there is no “first one wins” rule.

The other three are all true. A switch with no case at all compiles (and does nothing); default is optional, and control simply skips the switch if nothing matches; and omitting break is legal, producing fall-through.

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

Post your comment

Please log in or register to post a comment.