UMBC CS 201, Fall 98
The switch structure
The switch structure can often be used in place of a cascade of
if's.
Syntax
switch (E)
{
case C1 :
statements_1;
break;
case C2 :
statements_2;
break;
.
.
.
default :
statements_n;
break;
}
E is the control expression which
should evaluate to an integer.
the Ci's should be integer constants.
case C1: statements_1; break; is a
case clause
default: statements_n; break; is a
default clause
Semantics
- E is evaluated
- If E's value is equal to one of the Ci's, then control is
immediately transfered to that case.
- ...Otherwise, if there is a default clause, control is transferred
there.
- ......Otherwise, exit the switch.
- The statements in that selected case are evaluated.
- If a break is evaluated, control is transfered to the next
statement after the switch
Good programming practice
- include a break in every clause
- always include a default clause
CSEE
|
201
|
201 F'98
|
lectures
|
news
|
help
Wednesday, 16-Sep-1998 18:22:08 EDT