Consider the following switch statement:
switch( value )
{
case 1:
return 1;
default:
value++;
// fall-through
case 2:
return value * 2;
}
This code compiles, but is it valid (= defined behavior) for C90/C99? I have never seen code where the default case is not the last case.
EDIT:
As Jon Cage and KillianDS write: this is really ugly and confusing code and I am well aware of it. I am just interested in the general syntax (is it defined?) and the expected output.
The C99 standard is not explicit about this, but taking all facts together, it is perfectly valid.
A
caseanddefaultlabel are equivalent to agotolabel. See 6.8.1 Labeled statements. Especially interesting is 6.8.1.4, which enables the already mentioned Duff’s Device:Edit: The code within a switch is nothing special; it is a normal block of code as in an
if-statement, with additional jump labels. This explains the fall-through behaviour and whybreakis necessary.6.8.4.2.7 even gives an example:
The case constants must be unique within a switch statement:
All cases are evaluated, then it jumps to the default label, if given: