Sams Teach Yourself C in 21 Days

(singke) #1
Enter a value between 1 and 10, 0 to exit:
6
You entered 6 or more.

Enter a value between 1 and 10, 0 to exit:
0
This program accepts a value from the keyboard and then states whether the
value is 5 or less, 6 or more, or not between 1 and 10. If the value is 0 , line 18
executes a call to the exit()function, thus ending the program.
You can’t use breakin line 18, as you did in Listing 13.4 earlier. Executing a break
would merely break out of the switchstatement; it wouldn’t break out of the infinite
whileloop. The exit()function terminates the program. You’ll learn more about the
exit()function in the next section.

TheswitchStatement
switch (expression)
{
case template_1: statement(s);
case template_2: statement(s);
...
case template_n: statement(s);
default: statement(s);
}
Theswitchstatement allows for multiple branches from a single expression. It’s more
efficient and easier to follow than a multileveled ifstatement. A switchstatement evalu-
ates an expression and then branches to the casestatement that contains the template
matching the expression’s result. If no value matches the expression’s result, control goes
to the defaultstatement. If there is no defaultstatement, control goes to the end of the
switchstatement.
Program flow continues from the casestatement down unless a breakstatement is
encountered. If that occurs, control goes to the end of the switchstatement.
Example 1
switch( letter )
{
case ‘A’:
case ‘a’:
printf( “You entered A” );
break;
case ‘B’:
case ‘b’:
printf( “You entered B”);
break;

328 Day 13

ANALYSIS

,


S

YNTAX

,


21 448201x-CH13 8/13/02 11:12 AM Page 328

Free download pdf