Hardware Reference
In-Depth Information
The
switch
statement is a multiway decision based on the value of a control expression.
The syntax of the
switch
statement is
switch (
expression
) {
case const_expr
1
:
statement
1
;
break;
case const_expr
2
:
statement
2
;
break;
. . .
default:
statement
n
;
}
As an example, consider the following program fragment:
switch (i) {
case 1:
pay
5
100;
break;
case 2:
pay
5
200;
break;
case 3:
pay
5
300;
break;
case 4:
pay
5
400;
break;
case 5:
pay
5
500;
break;
default:
pay
5
0;
}
The variable
pay
receives a value that is equal to the value of
i
3
100
. The keyword
break
forces
the program flow to drop out of the
switch
statement so that only the statements under the cor-
responding
case-label
are executed. If any
break
statement is missing, then all the statements from
that case-label until the next
break
statement within the same
switch
statement will be executed.
The syntax of a
for-loop
statement is
for (expr1; expr2; expr3)
statement;
where
expr1
and
expr3
are assignments or function calls, and
expr2
is a relational expression.
For example, the following
for loop
computes the sum of the squares of integers from 1 to 9:
sum
5
0;
for (i
5
1; i
,
10; i
11
)
sum
5
sum
1
i * i;
Search WWH ::
Custom Search