When multiple statements are written in if()… else… statements where a single statement is expected, surprising results may occur. This is sometimes called thedangling else problem and is illustrated in the following code snippet:
if( x == 0 ) if( y == 0 ) printf( "y equals 0\n" );
else printf( "what does not equal 0\n" );
To whichif()… does the else… belong—the first one or the second one? To correct this possible ambiguity, it is often best to always use compound statements in if()… and else… clauses to make your intention unambiguous. Many compilers will give an error such as the following: warning: add explicit braces to avoid dangling else [-Wdangling-else].
On the other hand, some do not. The best way to remove doubt is to use brackets to associate the else…clause with the proper if()… clause. The following code snippet will remove both...