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

(Romina) #1

17. Making the case for the switch Statement


In This Chapter


  • Testing multiple cases with switch

  • Combining break with switch


The if statement is great for simple testing of data, especially if your data tests have only two or
three possibilities. You can use if to test for more than two values, but if you do, you have to nest
several if statements inside one another, and that can get confusing and hard to maintain.


Consider for a moment how you execute code based on a user’s response to a menu. A menu is a list
of options from which to select, such as this one:


What do you want to do?


  1. Add New Contact

  2. Edit Existing Contact

  3. Call Contact

  4. Text Contact

  5. Delete Contact

  6. Quit the Program
    What is your choice?


Note

When you create menus that ask for user input, you are creating a user interface.

It would take five if-else statements, nested inside one another, to handle all these conditions, as
you can see here:


Click here to view code image


if (userAns == 1)
{
// Perform the Add Contact Routine
}
else if (userAns == 2)
{
//Perform the Edit Contact Routine
}
else if (userAns == 3)
{
//Perform the Call Contact Routine
}
else if (userAns == 4)
{
//Perform the Text Contact Routine
}
else if (userAns == 5)
Free download pdf