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.
Theswitch
statement body consists of a series ofcase
tags and an optionaldefault
tag.case
Two constant expressions in a statement cannot evaluate to the same value.default
tag can only appear once. Marking statements is not a grammatical requirement, but if they are not present, theswitch
statements are meaningless. The default statement (i.e. thedefault
tag) does not need to appear at the end; it can appear anywhere in the body of the switch statement.case
ordefault
tags can only be displayed withinswitch
statements.Excerpted from: Microsoft Visual Studio 2015 c++ Switch statement official documentation
2.
The above-mentioned
case
anddefault
themselves 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 thebreak
statement orswitch
statement The scope ends.For this problem
STEP 1 : When
i=1
, sincei!=2&&i!=4
, execution starts after thedefault
label. 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 The
statement has not reached the end of the scope of theswitch
statement (because thisdefault
statement is placed first), so it then executes the statements aftercase 2
backwards (the compiler is no longer full at this time) Thecase
tag is not satisfied) At this time, the statementc++
is executed; after execution, the value of c is 2; when thebreak
statement is encountered, theswitch
statement is jumped out.STEP 3: When
i=2
, since i satisfiescase 2
, execution starts directly from the statement after thecase 2
note. At this time, the statementc++
is executed. After execution, c The value is 3. When thebreak
statement is encountered, theswitch
statement will be jumped out.STEP 4: When i=3, jump out of the
for
loop 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