Nasty Nested if and if-else-Statements
-
C++ has several constructs, called branching mechanisms,that allows a program to choose one out of a number of alternate actions depending on the circumstances.
Examples of these mechanisms are the if-else-statement, which is being discussed here, and the switch-statement, to be discussed shortly.
-
An if-else-statement is a two way branch. It allows a program to choose one out of two possible actions.
A multi-way branch is needed to choose one of three or more possible actions. It can be implemented using nested if-else statements which are discussed in more detail in the next section.
-
Nested if-else statements refers to having if-else-statements inside another
if-else-statement.
In the absence of braces, the compiler always pairs an else with the nearest (previous) if that is not already paired with some else.
In general, braces should be used especially in nested if-else-statements
to specify exactly what you want the compiler to do. This also help you and others to better understand you code.
-
A common error when there are if-else structures inside one another, and one is not using the braces, is to link the else to the wrong if. For example
if (Test1)
if (Test2)
Num = 2;
else
Num = 1;
It must be remembered that unless you use the braces to explicitly specify groupings,
the statement else belongs to the nearest if above it.
Therefore in the above example you must not be fooled by the alignment of the else with the first if. It forms a pair with the second if.
The above code is equivalent to the following much clearer code:
if (Test1)
{
if (Test2)
Num = 2;
else
Num = 1;
}
If you really want to associate the else with the first if,
then you must introduce the braces as follows:
if (Test1)
{
if (Test2) // Test1 true and Test2 true
Num = 2;
}
else
Num = 1; // Test1 false
-
//Another example illustrating the importance of using braces in nested if-else-statements.
#include <iostream>
using namespace std;
int main( )
{
double fuel_gauge_reading;
cout << "Enter fuel gauge reading: ";
cin >> fuel_gauge_reading;
cout << "First with braces:\n";
if (fuel_gauge_reading < 0.75)
{
if (fuel_gauge_reading < 0.25)
cout << "Fuel very low. Caution!\n";
}
else
{
cout << "Fuel over 3/4. Don't stop now!\n";
}
cout << "Now without braces:\n";
if (fuel_gauge_reading < 0.75)
if (fuel_gauge_reading < 0.25)
cout << "Fuel very low. Caution!\n";
else
cout << "Fuel over 3/4. Don't stop now!\n";
return 0;
}