Sams Teach Yourself C in 21 Days

(singke) #1
Advanced Program Control 329

13


default:
printf( “I don’t have a case for %c”, letter );
}
Example 2
switch( number )
{
case 0: puts( “Your number is 0 or less.”);
case 1: puts( “Your number is 1 or less.”);
case 2: puts( “Your number is 2 or less.”);
case 3: puts( “Your number is 3 or less.”);

case 99: puts( “Your number is 99 or less.”);
break;
default: puts( “Your number is greater than 99.”);
}
Because there are no breakstatements for the first casestatements, this example finds
thecasethat matches the number and prints every casefrom that point down to the
breakincase 99. If the number was 3 , you would be told that your number is equal to 3
or less, 4 or less, 5 or less, up to 99 or less. The program continues printing until it
reaches the breakstatement in case 99.

,


,


DOuse a defaultcase in a switchstate-
ment, even if you think you’ve covered
all possible cases.
DOuse a switchstatement instead of an
ifstatement if more than two condi-
tions are being evaluated for the same
variable.
DOline up your casestatements so that
they’re easy to read.

DON’Tforget to use breakstatements if
yourswitchstatements need them.

DO DON’T


Exiting the Program ............................................................................................


A C program normally terminates when execution reaches the closing brace of the
main()function. However, you can terminate a program at any time by calling the
library function exit(). You can also specify one or more functions to be automatically
executed at termination.

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

Free download pdf