- Putting the initial brace after the condition and aligning the closing brace under the
ifto close the statement block:
if (expression){
statements
} - Aligning the braces under the ifand indenting the statements:
if (expression)
{
statements
} - Indenting the braces and statements:
if (expression)
{
statements
}
This book uses the middle alternative because it is easy to understand where blocks of
statements begin and end if the braces line up with each other and with the condition
being tested. Again, it doesn’t matter which style you choose, so long as you are consis-
tent with it.
The elseStatement ..........................................................................................
Often, your program needs to take one branch if your condition is true, or another if it is
false. In Listing 4.4, you wanted to print one message (Let’s Go Mets!) if the first test
(MetsScore > YankeesScore) evaluated true, and another message (Go Yankees!) if it
evaluated false.
The method shown so far—testing first one condition and then the other—works fine but
is a bit cumbersome. The keyword elsecan make for far more readable code:
if (expression)
statement;
else
statement;
Listing 4.5 demonstrates the use of the keyword else.
LISTING4.5 Demonstrating the elseKeyword
1: // Listing 4.5 - demonstrates if statement
2: // with else clause
3: #include <iostream>
4: int main()
5: {
84 Day 4