X hits on this document





184 / 396

Chapter ‎18   Unsafe code

is valid because no switch section has a reachable end point. Unlike C and C++, execution of a switch section is not permitted to “fall through” to the next switch section, and the example

switch (i) { case 0: CaseZero(); case 1: CaseZeroOrOne(); default: CaseAny(); }

results in a compile-time error. When execution of a switch section is to be followed by execution of another switch section, an explicit goto case or goto default statement must be used:

switch (i) { case 0: CaseZero(); goto case 1; case 1: CaseZeroOrOne(); goto default; default: CaseAny(); break; }

Multiple labels are permitted in a switch-section. The example

switch (i) { case 0: CaseZero(); break; case 1: CaseOne(); break; case 2: default: CaseTwo(); break; }

is valid. The example does not violate the “no fall through” rule because the labels case 2: and default: are part of the same switch-section.

The “no fall through” rule prevents a common class of bugs that occur in C and C++ when break statements are accidentally omitted. In addition, because of this rule, the switch sections of a switch statement can be arbitrarily rearranged without affecting the behavior of the statement. For example, the sections of the switch statement above can be reversed without affecting the behavior of the statement:

Copyright Microsoft Corporation 1999-2003. All Rights Reserved.171

Document info
Document views352
Page views352
Page last viewedWed Aug 10 03:24:59 UTC 2016