Read Sams Teach Yourself C in 24 Hours Online
Authors: Tony. Zhang
The general form of the switch statement is
switch (expression) {
case constant-expression1:
statement1;
case constant-expression2:
13 067231861x CH10 4.10.2000 11:02 AM Page 162
162
Hour 10
statement2;
.
.
.
default:
statement-default;
}
Here the conditional expression, expression, is evaluated first. The switch statement will then jump to the proper case label and execute, in order, whatever statements follow. If expression yields a value equal to the constant expression constant-expression1, the statement statement1 is executed, followed by statement2 and everything on down to statement-default. If the value yielded by expression is the same as the value of constant-expression2, statement2 is executed first. If, however, the value of expression is not equal to any values of the constant expressions labeled by the case keyword, the statement (statement-default) following the default keyword is executed.
You have to use the case keyword to label each case. Note that each case label ends with a
colon
, not a semicolon. This is the syntax for labels in C. The default keyword should be used for the “default” case — that is, when no case label matches with the conditional expression. Note that none of the constant expressions associated with case labels may be identical within the switch statement.
In C, a
label
is used as a kind of bookmark in your code for use by the conditional branching statement. A label is not, itself, a statement; rather, it points to a place to jump when you want to depart from the normal top-down flow of execution.
The proper syntax for a label is a unique identifier followed by a colon —
not a semicolon . In this chapter you will see several ways to use labels, as well as the reserved label names case expression: and default:.
The program in Listing 10.4 gives you an example of using the switch statement. The program also demonstrates an important feature of the switch statement.
LISTING 10.4
Using the switch Statement
1: /* 10L04.c Using the switch statement */
2: #include
3:
4: main()
5: {
6: int day;
13 067231861x CH10 4.10.2000 11:02 AM Page 163
Controlling Program Flow
163
7:
8: printf(“Please enter a single digit for a day\n”);
9: printf(“(within the range of 1 to 3):\n”);
10: day = getchar();
11: switch (day){
12: case ‘1’:
13: printf(“Day 1\n”);
14: case ‘2’:
15: printf(“Day 2\n”);
16: case ‘3’:
17: printf(“Day 3\n”);
18: default:
19: ;
20: }
21: return 0;
22: }
10
If I run the executable file 10L04.exe and enter 3, I obtain the following output: Please enter a single digit for a day
OUTPUT
(within the range of 1 to 3):
3
Day 3
As you can see in line 6, an int variable, day, is declared; it is assigned the input
ANALYSIS
entered by the user in line 10.
In line 11, the value of the integer variable day is evaluated in the switch statement. If the value is equal to one of the values of the constant expressions, the computer starts to execute statements from there. The constant expressions are labeled by prefixing case in front of them.
For instance, I entered 3 and then pressed the Enter key. The numeric value of 3 is assigned to day in line 10. Then, after finding a case in which the value of the constant expression matches the value contained by day, the computer jumps to line 17 to execute the printf() function and display Day 3 on the screen.
Note that under the default label in Listing 10.4, there is an empty (that is, null) statement ending with semicolon in line 19. The computer does nothing with the empty statement. This means that if none of the constant expressions apply, then the switch statement ends up doing nothing at all.
However, if I enter 1 from my keyboard and then press the Enter key when running executable file 10L04.exe, I get the following output:
Please enter a single digit for a day
13 067231861x CH10 4.10.2000 11:02 AM Page 164
164
Hour 10
(within the range of 1 to 3):
1
Day 1
Day 2
Day 3
From the output, you can see that the statement controlled by the selected case, case 1, and the statements controlled by the rest of the cases, are executed, because Day 1, Day 2, and Day 3 are displayed on the screen. Likewise, if I enter 2 from my keyboard, I have Day 2 and Day 3 shown on the screen.
This is an important feature of the switch statement: The computer continues to execute the statements following the selected case until the end of the switch statement.
You’re going to learn how to exit early from the execution of the switch statement in the next section.
The
break
Statement
If you want to exit the switch entirely after each case label, you can add a break statement at the end of the statement list that follows every case label. The break statement simply exits the switch and resumes execution after the end of the switch statement block.
The program in Listing 10.5 looks similar to the one in Listing 10.4, but this time, the break statement is used and there are different results.
LISTING 10.5
Adding the break Statement
1: /* 10L05.c Adding the break statement */
2: #include
3:
4: main()
5: {
6: int day;
7:
8: printf(“Please enter a single digit for a day\n”);
9: printf(“(within the range of 1 to 7):\n”);
10: day = getchar();
11: switch (day){
12: case ‘1’:
13: printf(“Day 1 is Sunday.\n”);
14: break;
15: case ‘2’:
16: printf(“Day 2 is Monday.\n”);
17: break;
18: case ‘3’:
19: printf(“Day 3 is Tuesday.\n”);
13 067231861x CH10 4.10.2000 11:02 AM Page 165
Controlling Program Flow
165
20: break;
21: case ‘4’:
22: printf(“Day 4 is Wednesday.\n”);
23: break;
24: case ‘5’:
25: printf(“Day 5 is Thursday.\n”);
26: break;
27: case ‘6’:
28: printf(“Day 6 is Friday.\n”);
29: break;
30: case ‘7’:
31: printf(“Day 7 is Saturday.\n”);
32: break;
33: default:
34: printf(“The digit is not within the range of 1 to 7.\n”);
35: break;
36: }
10
37: return 0;
38: }
With help from the break statement, I can run the executable file 10L05.exe and obtain only the output of the selected case:
Please enter a single digit for a day
OUTPUT
(within the range of 1 to 7):
1
Day 1 is Sunday.
This program has seven case labels followed by the constant expressions of ‘1’,
ANALYSIS
‘2’, ‘3’, ‘4’, ‘5’, ‘6’, and ‘7’, respectively. (See lines 12, 15, 18, 21, 24, 27, and 30.)
In each case, there is one statement followed by a break statement. As mentioned, the break statements will exit the switch construct before the computer ever gets to the next case label and the statements that follow it.
For example, after the int variable day is assigned the value of 1 and evaluated in the switch statement, the case with ‘1’ is selected, and the statement in line 13 is executed.
Then, the break statement in line 14 is executed, which breaks the control of the switch statement and returns the control to the next statement outside the switch construct. In Listing 10.5, the next statement is the return statement in line 37, which ends the main function.
The printf() call in line 13 outputs a string of Day 1 is Sunday. on the screen.
Note that in a switch statement, braces are not needed to group the statements within an individual case, since case is just a label and does not control the statements that follow it. They are simply executed in order, starting with the label.
13 067231861x CH10 4.10.2000 11:02 AM Page 166
166
Hour 10
Breaking an Infinite Loop
You can also use the break statement to break an infinite loop. An infinite loop is one in which the conditional expression is left out entirely; thus, it is up to the code inside the loop to determine the conditions for ending the loop. The following are examples of infinite for and while loops:
for (;;){
statement1;
statement2;
.
.
.
}
while {
statement1;
statement2;
.
.
.
}
The for loop above leaves out all three expressions. This causes the for statement to always execute the loop. The while statement uses 1 as its conditional expression, and since this of course never evaluates to 0, the while statement always continues the loop.
The program in Listing 10.6 shows an example of using the break statement in an infinite while loop.
LISTING 10.6
Breaking an Infinite Loop
1: /* 10L06.c: Breaking an infinite loop */
2: #include
3:
4: main()
5: {
6: int c;
7:
8: printf(“Enter a character:\n(enter x to exit)\n”);
9: while {
10: c = getc(stdin);
11: if (c == ‘x’)
12: break;
13: }
14: printf(“Break the infinite while loop. Bye!\n”);
15: return 0;
16: }
13 067231861x CH10 4.10.2000 11:02 AM Page 167
Controlling Program Flow
167
The following is the result I got after running the executable file (10L06.exe) on my machine:
Enter a character:
OUTPUT
(enter x to exit)
H
I
x
Break the infinite while loop. Bye!
There is an infinite while loop in Listing 10.6, which starts in line 9 and ends in
ANALYSIS
line 13. Within the infinite loop, the characters entered by the user are assigned, one at a time, to the integer variable c (see line 10.)
The relational expression c == ‘x’ in the if statement (see line 11) is evaluated each time during the looping. If the expression evaluates to a value of 0 (that is, the user has
10
not entered the letter x), the looping continues. Otherwise, the break statement in line 12
is executed, which causes the computer to jump out of the infinite loop and start executing the next statement, which is shown in line 14.
You can see in the sample output, the while loop continues until I have entered the letter x, which causes the infinite loop to be broken and a message, Break the infinite while loop. Bye!, to be displayed on the screen.
The
continue
Statement
Instead of breaking a loop, there are times when you want to stay in a loop but skip over some statements within the loop. To do this, you can use the continue statement. The continue statement causes execution to jump to the bottom of the loop immediately.
For example, Listing 10.7 demonstrates how to use the continue statement in a loop doing sums.
LISTING 10.7
Using the continue Statement
1: /* 10L07.c: Using the continue statement */
2: #include
3:
4: main()
5: {
6: int i, sum;
7:
8: sum = 0;
9: for (i=1; i<8; i++){
10: if ((i==3) || (i==5))
11: continue;
continues
13 067231861x CH10 4.10.2000 11:02 AM Page 168
168
Hour 10
LISTING 10.7
continued
12: sum += i;
13: }
14: printf(“The sum of 1, 2, 4, 6, and 7 is: %d\n”, sum);
15: return 0;
16: }
After the executable file 10L07.exe is run on my computer, the following output is shown on the screen:
The sum of 1, 2, 4, 6, and 7 is: 20
OUTPUT
In Listing 10.7, we want to calculate the sum of the integer values of 1, 2, 4, 6,
ANALYSIS
and 7. Because the integers are almost consecutive, a for loop is built in lines 9–13. The statement in line 12 sums all consecutive integers from 1 to 7 (except for 3
and 5, which aren’t in the listing and are skipped in the for loop).
To skip these two numbers, the expression (i==3) || (i==5) is evaluated in the if statement of line 10. If the expression evaluates to 1 (that is, the value of i is equal to either 3 or 5), the continue statement in line 11 is executed, which causes the sum operation in line 12 to be skipped, and another iteration to be started at the for statement. In this way, you obtain the sum of the integer values of 1, 2, 4, 6, and 7, but skip 3 and 5, automatically by using one for loop.
After the for loop, the value of sum, 20, is displayed on the screen by the printf() call in the statement of line 14.
The
goto
Statement
This book would not be complete without mentioning the goto statement, although I do not recommend that you use the goto statement. The main reason that the goto statement is discouraged is because its usage is likely to make the C program unreliable and hard to debug.
Programmers are often tempted to use the goto statement, especially if they have used other languages without the rich set of structured conditional branching statements that C provides. The fact is, any use of goto can be avoided entirely by using the other branching statements.