Next: Summary Up: Introduction to C++ Programming Previous: Exercises


Nested if and if-else statements

The if-else statement allows a choice to be made between two possible alternatives. Sometimes a choice must be made between more than two possibilities. For example the sign function in mathematics returns -1 if the argument is less than zero, returns +1 if the argument is greater than zero and returns zero if the argument is zero. The following C++ statement implements this function:

if (x < 0)
   sign = -1;
else
   if (x == 0)
      sign = 0;
   else
      sign = 1;

This is an if-else statement in which the statement following the else is itself an if-else statement. If x is less than zero then sign is set to -1, however if it is not less than zero the statement following the else is executed. In that case if x is equal to zero then sign is set to zero and otherwise it is set to 1.

Novice programmers often use a sequence of if statements rather than use a nested if-else statement. That is they write the above in the logically equivalent form:

if (x < 0)
   sign = -1;
if (x == 0)
   sign = 0;
if (x > 0)
   sign = 1;

This version is not recommended since it does not make it clear that only one of the assignment statements will be executed for a given value of x. Also it is inefficient since all three conditions are always tested.

If nesting is carried out to too deep a level and indenting is not consistent then deeply nested if or if-else statements can be confusing to read and interpret. It is important to note that an else always belongs to the closest if without an else.

When writing nested if-else statements to choose between several alternatives use some consistent layout such as the following:

if ( condition1 )
statement1 ;
else if ( condition2 )
statement2 ;
. . .
else if ( condition-n )
statement-n ;
else
statement-e ;

Assume that a real variable x is known to be greater than or equal to zero and less than one. The following multiple choice decision increments count1 if 0 $\leq$ x $<$ 0.25, increments count2 if 0.25 $\leq$ x $<$ 0.5, increments count3 if 0.5 $\leq$ x $<$ 0.75 and increments count4 if 0.75 $\leq$ x $<$ 1.

if (x < 0.25)
  count1++;
else if (x < 0.5)
  count2++;
else if (x < 0.75)
  count3++;
else
  count4++;

Note how the ordering of the tests here has allowed the simplification of the conditions. For example when checking that x lies between 0.25 and 0.50 the test x < 0.50 is only carried out if the test x < 0.25 has already failed hence x is greater than 0.25. This shows that if x is less than 0.50 then x must be between 0.25 and 0.5.

Compare the above with the following clumsy version using more complex conditions:

if (x < 0.25)
  count1++;
else if (x >= 0.25 && x < 0.5)
  count2++;
else if (x >= 0.5 && x < 0.75)
  count3++;
else
  count4++;



Subsections
Next: Summary Up: Introduction to C++ Programming Previous: Exercises