< previous page page_211 next page >

Page 211
else if (month == 2)          // Nested If
    cout << February;
else if (month == 3)          // Nested If
    cout << March;
else if (month == 4)          // Nested If
  .
  .
  .
else
    cout << December;
This style prevents the indentation from marching continuously to the right. But, more importantly, it visually conveys the idea that we are using a 12way branch based on the variable month.
It's important to note one difference between the sequence of If statements and the nested If: More than one alternative can be taken by the sequence of Ifs, but the nested If can select only one. To see why this is important, consider the analogy of filling out a questionnaire. Some questions are like a sequence of If statements, asking you to circle all the items in a list that apply to you (such as all your hobbies). Other questions ask you to circle only one item in a list (your age group, for example) and are thus like a nested If structure. Both kinds of questions occur in programming problems. Being able to recognize which type of question is being asked permits you to immediately select the appropriate control structure.
Another particularly helpful use of the nested If is when you want to compare a series of consecutive ranges of values. For example, the first Problem-Solving Case Study in this chapter involves printing different messages for different ranges of temperatures. We present two solutions for one of the modules, one using a sequence of If statements, the other using a nested If structure. As you'll see, the nested If version uses fewer comparisons, so it's more efficient.
As fast as modern computers are, many applications require so much computation that inefficient algorithms can waste hours of computer time. Always be on the lookout for ways to make your programs more efficient, as long as doing so doesn't make them difficult for other programmers to understand. It's usually better to sacrifice a little efficiency for the sake of readability.
The Dangling Else
When If statements are nested, you may find yourself confused about the if-else pairings: To which if does an else belong? For example, suppose that if a student's average is below 60, we want to print Failing; if it is at least 60 but less than 70, we want to print Passing but marginal; and if it is 70 or greater, we don't want to print anything.

 
< previous page page_211 next page >