| C Tutorial | Switch statement | |||
|
If Statement Ternary Operator Switch Statement While Loop Do-While Loop For Loop Break Continue
|
The switch statement is a sort of specialized form of if used to efficiently separate different blocks of code based on the value of an integer. The switch expression is evaluated, and then the flow of control jumps to the matching const-expression case. The case expressions are typically int or char constants. The switch statement is probably the single most syntactically awkward and error-prone features of the C language.
switch (<expression>) { case <const-expression-1>: <statement> break;
case <const-expression-2>: <statement> break;
case <const-expression-3>: // here we combine case 3 and 4 case <const-expression-4>: <statement> break;
default: // optional <statement> }
Each constant needs its own case keyword and a trailing colon (:). Once execution has jumped to a particular case, the program will keep running through all the cases from that point down -- this so called "fall through" operation is used in the above example so that expression-3 and expression-4 run the same statements. The explicit break statements are necessary to exit the switch. Omitting the break statements is a common error -- it compiles, but leads to inadvertent fall-through behavior.
Why does the switch statement fall-through behavior work the way it does? The best explanation I can think of is that originally C was developed for an audience of assembly language programmers. The assembly language programmers were used to the idea of a jump table with fall-through behavior, so that's the way C does it (it's also relatively easy to implement it this way.) Unfortunately, the audience for C is now quite different, and the fall-through behavior is widely regarded as a terrible part of the language.
Want To Know more with Video ??? |
|