What suffix is chosen if (count+1)
is equal to 5?
suffix = "th";
if ( count+1 == 2 ) <--- false: go to false branch suffix = "nd"; else if ( count+1 == 3 ) <--- false: go to inner false branch suffix = "rd"; else suffix = "th"; <--- inner false branch executed
The fragment shows how the nested if
works when
(count+1)
is equal to 5.
The outer if
is false,
so its false-branch is chosen.
Now the if
of that branch (the nested if
)
tests (count+1)
and picks its false-branch.
When (count+1)
is 4 or greater the "th" suffix is chosen.
It is sometimes hard to see exactly how the if's and else's nest in
programs like this.
Braces can show what matches what,
but here is a rule that works without braces.
Rule: Start with the first if
and scan downward.
Each else
matches the first
unmatched if
above it.
An if
matches only one
else
and an else
matches only one if
.
Continue scanning until you reach the end.
Every else
should be matched with a single if
.
if ( count+1 == 2 ) suffix = "nd"; else if ( count+1 == 3 ) suffix = "rd"; else suffix = "th";
In the above, start at the top. Scan downward and find the first unmatched else . Match it with the unmatched if above it. Continue scanning downward. Find the next else, match it with the first unmatched if above it.
Indent the program to show the matching if's and else's. But remember that the compiler does not pay any attention to indenting.
Here is another example.
If you follow the rule,
the else
matches the if
above it.
The first if
has no matching else
.
if ( a == -5 ) abs = 5; if ( a == -7 ) abs = 7 else abs = 10
Here is another example.
It is not indented properly.
Use the rule
to figure out which if
s and else
s match.
(Mouse over if
s to see their match.)
if ( a == b ) if ( d == e ) total = 0; else total = total + a; else total = total + b;