Can some one please explain the nesting of case
statements into another. I'm referring to the Duffs Device where all other case
statements are inside the do-while
loop associated with case 0
. I cant get my head around it. It seems to me that it should act like a nested if
. But then i'm definitely missing something. Please explain.
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
The easiest way to understand Duff's device is to separate its two logical components, the
switch
and thedo/while
loop, from each other. Here is a logically equivalent implementation, where the two statements are no longer nested:Note the labels inside the loop: they are normal C labels, not
case
labels.The only difference between this code and Duff's device is that Duff's code exploits the ability of using
case
labels inside ado/while
loop, as long as the loop itself starts and ends inside theswitch
statement, eliminating the need for "regular" labels and gotos.In a
switch-case
construct, theswitch
body is just a normal or compound statement which can contain any other valid c statements. It may also containcase
ordefault
labels.And the control jumps to appropriate case label depending on controlling expression value, the statements in the switch body are executed one after another just like any other scope
{
}
unless abreak
is encountered.For example, consider the following simple test program:
Consider 3 values for the controlling expression
i
in theswitch
statement:The resultant outputs are as follows:
Scenario 1:
i = 6
Scenario 2:
i = 10
Scenario 3:
i = 5
Notice that, in each of the above scenarios, once a matching
case
label is encountered the statements are executed sequentially until abreak
is encountered, Thereby leading to conclusion which is the first statement in the answer.