Warning
Anytime you need to terminate a program before its natural conclusion, use the
exit() function. The value you place in the exit() parentheses is returned to your
operating system. Most beginning programmers ignore the return value and put either a
0 or a 1 in the parentheses. You must remember to add <stdlib.h> with the
#include directive in every program that uses exit().
The do-while loop keeps the user honest. If the user enters something other than a number from 1 to
5, the ...is not a valid choice. message prints, thanks to the default keyword. C
ensures that if none of the other cases matches the variable listed after switch, the default
statements execute.
default works like else, in a way. else takes care of an action if an if test is false, and
default takes care of an action if none of the other case conditions successfully matches the
switch variable. Although default is optional (as is else), it’s good programming practice to
use a default to handle unexpected switch values.
Tip
The switch variable can be either an integer or a character variable. Do not use a
float or a double for the switch test.
break and switch
The switch statement shown earlier has several break statements scattered throughout the code.
The break statements ensure that only one case executes. Without the break statements, the
switch would “fall through” to the other case statements. Here is what would happen if the
break statements were removed from the switch and the user answered with a choice of 2 :
Click here to view code image
Get ready to enter the name of the
contact you wish to change.
Which contact do you wish to call?
Which contact do you wish to text?
The break keeps switch case statements from running together.
Note
The only reason the default condition’s message did not print is that the exit()
function executed inside case ( 5 ).