Chapter 5: Control Statements 79
if (bytesAvailable > 0) {
ProcessData();
bytesAvailable -= n;
} else {
waitForMoreData();
bytesAvailable = n;
}
Nested ifs
Anestedifis anifstatement that is the target of anotheriforelse. Nestedifs are very common
in programming. When you nestifs, the main thing to remember is that anelsestatement
always refers to the nearestifstatement that is within the same block as theelseand that is
not already associated with anelse. Here is an example:
if(i == 10) {
if(j < 20) a = b;
if(k > 100) c = d; // this if is
else a = c; // associated with this else
}
else a = d; // this else refers to if(i == 10)
As the comments indicate, the finalelseis not associated withif(j<20)because it is not
in the same block (even though it is the nearestifwithout anelse). Rather, the finalelse
is associated withif(i==10). The innerelserefers toif(k>100)because it is the closestif
within the same block.
The if-else-if Ladder
A common programming construct that is based upon a sequence of nestedifsisthe
if-else-if ladder. It looks like this:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
.
.
.
else
statement;
Theifstatements are executed from the top down. As soon as one of the conditions controlling
theifistrue, the statement associated with thatifis executed, and the rest of the ladder is
bypassed. If none of the conditions is true, then the finalelsestatement will be executed.
The finalelseacts as a default condition; that is, if all other conditional tests fail, then the