C Programming Lecture 11
The switch Statement The switch statement is a multiway conditional statement generalizing the if-else statement.
switch switch (expression) { case constant1: statement . . . statement case constant_n: statement default : statement } /* end switch */
The break Statement The break statement causes a jump out of a switch statement. Execution continues after the closing brace of the switch statement.
Example Using the switch Statement switch (val) { case 1: ++a_cnt; break; case 2: case 3: ++b_cnt; default: ++other_cnt; } The val expression must be of an integer type. The constant integral expressions following the case labels must all be unique.
The Effect of a switch Statement Evaluate the switch expression. Go to the case label having a constant value that matches the value of the expression found in step 1. If a match is not found, go to the default label. If there is no default label, terminate the switch. Terminate the switch when a break statement is encountered, or by “falling off the end”.
Bell Labs Industrial Programming Style Follow normal rules of English, where possible. e.g., put a space after a comma Put one space on either side of a binary operator. Indent code in a consistent fashion to indicate flow of control. Put braces as indicated in the following example: for (i = 0; i < n; ++i) { . . . /* indent 3 spaces */ }
Student Style Place beginning and ending braces in the same column. while (i < 10) { . . . } Either style for braces is acceptable in our class.
Misuse of Relational Operators int k = 8; if (2 < k < 7) printf(“true”); /*true is printed*/ else printf(“false”); if (2 < k && k < 7) printf(“true); printf(“false”); /*false is printed*/