#172 – Nested if Statements

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();
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #172 – Nested if Statements

  1. Your humor in these posts is not lost on me. The “DoWhateverWifeSays()” method is my favorite by far!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: