C Switch Statement with Examples
The C switch statement is multi-way decision that tests whether an expression matches one of number of constant integer values, and branches accordingly.
The switch is multi way conditional statement generalizing the if-else statement. Let us first look at the syntax for a switch statement.
switch (expression) { case const-expr: statements case const-expr i statements default: statements }
Each case is labelled by one or more integer-valued constants or constant expressions.
If case matches the expression value, execution starts at that case. All case expressions must be different. The case labelled default is executed if none of the other cases are satisfied.
The following is a typical example program of C switch statement:
switch (c) { case 'a'; ++a....cnt; break; case 'b': case 'B I: ++b_cnt; break; default: ++other_cnt; }
Notice that the body of the C switch statement in the example is a compound statement. This will be so in all but the most degenerate situations. A default is optional; if it isn’t there and if none of the cases match, no action at all takes place. Cases and the default clause can occur in any order.
C switch statement
Here is the same program with C switch:
#include <stdio.h> main() 1* count digits, white space, others *1 { int c, i, nwhite, nother, ndigit[10]; nwhite = nother = 0; for (i = 0; i < 10; i++) ndigit[i] = 0; while «c = getchar(» 1= EOF) { switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': ndigit[c-'O']++; break; case ‘ ‘; case ‘\n’; case ‘\t’; nwhite++; break; default: nother++; break; } } printf("digits ="); for (i = 0; i < 10; i++) printf(n %dn, ndigit[i]); print~(n, whit:e space = %d, other = %d\n", nwhite, nother); return 0; }
The break statement causes an immediate exit from the switch. Because cases serve just as labels, after the code for one case is done, execution falls through to the next unless you take explicit action to escape. break and return are the most common ways to leave a switch.
Let us review the various kinds of jump statements available to us. These include the goto, break, continue, and return statements. The goto is unrestricted in its use and should be avoided as a dangerous construct. The break may be used in loops and is important to the proper structuring of the switch statement. Typically, it occurs last, although it can occur anywhere. The keywords case and default cannot occur outside of C switch statement.
Please write your comments if you find anything incorrect OR need to explain in detail, or you want to share more information about the topic discussed above.