"Frederick Dean" <di*******@tom.comwrote in message
news:e8**********@news.cn99.com...
: Hi,guys!
: I'm reading Stephen Dewhurst's book "C++ Gotchas"£¬in gothca #7, I
: meet a weird case:
[...]
: I can't understand how the case goes, those cases are not even in the
: same level, the author does not explain how the cases execute, could you
: please help me with this? Any help is appreciated, thanks!
The loss of indentation in your post makes it even more difficult
to read this code.
I would guess that this example intends to illustrate that
the "case" labels of a switch statement are pretty much like
the labels of a goto: they can be used to jump anywhere within
other bracketed statements
[provided that no variable initialization is skipped].
switch(i) {
case a: ...
case b: ...
default: ...
}
is equivalent to:
if(i==a) goto label_a;
else if(i==b) goto label_b; //NB: i is not re-evaluated
else goto label_default;
{
label_a: ...
label_b: ...
label_default: ...
}
This can sometimes be abused to implement state machines
(as appears to be the case in the provided example) or
other nifty tricks (ever heard of Duff's device? see
http://en.wikipedia.org/wiki/Duff's_device).
But these special switch tricks are never a good idea,
except if the code is much messier without them...
[ as is the case for usage of goto ]
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <
http://www.brainbench.com