#172 – Nested if Statements
December 6, 2010 2 Comments
The statement to be executed when an if statement’s boolean expression resolves to true can be another if statement.
if (bob.IsSingle) if (TheGameIsOnToday()) WatchGame(); else PlayVideoGames();
Because the inner if/else is a single statement, it can follow the boolean expression of the outer if as the single statement to execute if the expression resolves to true.
This might lead to some confusion about which if statement the else applies to. An else clause belongs to the last if that doesn’t have an else clause.
You could make this logic more clear by enclosing the inner if/else in braces.
if (bob.IsSingle) { if (TheGameIsOnToday()) WatchGame(); else PlayVideoGames(); } else DoWhateverWifeSays();