int c,i;
for (int i = 1; i < 3; ++i)
{
switch (i)
{
default: c+=i;
case 2: c++;break;
case 4: c+=2;break;
}
}
printf("%d\n", c);
Why is this code equal to 3? Isn't this the case where default: c =i; is used when i is 1 for the first time, and case 2: c ;break; is used when i is 2 for the second time? Then it ends, and c=2 is output in the end? Why is it 3?
First of all, let’s clarify some points to note in switch:
1.
Theswitchstatement body consists of a series ofcasetags and an optionaldefaulttag.caseTwo constant expressions in a statement cannot evaluate to the same value.defaulttag can only appear once. Marking statements is not a grammatical requirement, but if they are not present, theswitchstatements are meaningless. The default statement (i.e. thedefaulttag) does not need to appear at the end; it can appear anywhere in the body of the switch statement.caseordefaulttags can only be displayed withinswitchstatements.Excerpted from: Microsoft Visual Studio 2015 c++ Switch statement official documentation
2.
The above-mentioned
caseanddefaultthemselves are labels, which tell the compiler to start executing backwards when this label is satisfied, and then it will not judge the correctness of other labels until thebreakstatement orswitchstatement The scope ends.For this problem
STEP 1 : When
i=1, sincei!=2&&i!=4, execution starts after thedefaultlabel. At this time, the statementc+=i;(we now assume that compilation The compiler will help you initialize c to 0. You must know that not all compilers are so friendly) The value of c after execution is 1;STEP 2: Based on the above 1 and 2, it can be seen that since no
break is encountered at this time Thestatement has not reached the end of the scope of theswitchstatement (because thisdefaultstatement is placed first), so it then executes the statements aftercase 2backwards (the compiler is no longer full at this time) Thecasetag is not satisfied) At this time, the statementc++is executed; after execution, the value of c is 2; when thebreakstatement is encountered, theswitchstatement is jumped out.STEP 3: When
i=2, since i satisfiescase 2, execution starts directly from the statement after thecase 2note. At this time, the statementc++is executed. After execution, c The value is 3. When thebreakstatement is encountered, theswitchstatement will be jumped out.STEP 4: When i=3, jump out of the
forloop and output c=3;(The above process is the conclusion drawn by me using Visual Studio 2015 single-step debugging and combined with the data)
When i=1, it enters default: c=1 and there is no break, so continue to match case 2 and get c=2 break
When i=2, it matches case 2 first and enters case 2: c=3 break
When i=3 The cycle does not hold.
The output c is 3