Here is the example fragment properly indented
and with matching if
s and else
s colored the same.
if ( a == b ) if ( d == e ) total = 0; else total = total + a; else total = total + b;
Sometimes you must use braces { and }
to say what you want.
An else
inside of a pair of braces
must match an if
also inside that pair.
Sometimes you don't need braces,
but use them
to make clear (to human readers) what you intend.
Here is the complete rule for matching
if
s and else
s:
Rule for Matching if and else: Within each pair of matching braces: start with the firstif
and work downward. Eachelse
matches the closest previous unmatchedif
. Anif
matches only oneelse
and anelse
matches only oneif
.
Here is a program fragment that uses braces:
if ( ch == 'q' ) { if ( sum == 12 ) ch = 'b' ; } else ch = 'x' ;
The blue if
and blue else
match.
Without the braces, they would not match.
Here is another, poorly indented, fragment:
if ( a == b ) { if ( d == e ) total = 0; else total = total + b; }
Match the if
s and else
s.