C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1
{
//Perform the Delete Contact Routine
}
else
{
//Perform the Quit Routine
}

Nothing is wrong with nested if statements, but the C switch statement is clearer for multiple
conditions.


Making the switch


The switch statement has one of the longest formats of any statement in C (or just about any other
language). Here is the format of switch:


Click here to view code image


switch (expression)
{
case (expression1): { one or more C statements; }
case (expression2): { one or more C statements; }
case (expression3): { one or more C statements; }
// This would keep going for however many case statements to test
default: { one or more C statements; }

Tip

As with most statements, the actual use of switch is a lot less intimidating than its
format leads you to believe.

The menu shown earlier is perfect for a series of function calls. The problem is that this book has not
yet discussed function calls, except for a handful of built-in functions such as printf() and
scanf(). The following simple program uses a switch statement to print an appropriate message,
depending on the choice the user makes.


Tip

Ordinarily, a function call would replace the printf() statements you see after each
case. After you read Chapter 31, “Passing Variables to Your Functions,” you’ll
understand how to use function calls to perform case actions.

Click here to view code image


// Example program #1 from Chapter 17 of Absolute Beginner's Guide
// to C, 3rd Edition
// File Chapter17ex1.c
Free download pdf