Each statement can be either a single statement or a statement block delimited by braces (see Figure 6.2). The entire if else construct counts syntactically as a single statement.
Figure 6.2. The structure of if else statements.
For example, suppose you want to alter incoming text by scrambling the letters while keeping the newline character intact. In that case, each line of input is converted to an output line of equal length. This means you want the program to take one course of action for newline characters and a different course of action for all other characters. As Listing 6.2 shows, if else makes this task easy. The listing also illustrates the std:: qualifier, one of the alternatives to a using directive.
Listing 6.2. ifelse.cpp
// ifelse.cpp -- using the if else statement
#include
int main()
{
char ch;
std::cout << "Type, and I shall repeat.\n";
std::cin.get(ch);
while (ch != '.')
{
if (ch == '\n')
std::cout << ch; // done if newline
else
std::cout << ++ch; // done otherwise
std::cin.get(ch);
}
// try ch + 1 instead of ++ch for interesting effect
std::cout << "\nPlease excuse the slight confusion.\n";
// std::cin.get();
// std::cin.get();
return 0;
}
Here’s some sample output from the program in Listing 6.2:
Type, and I shall repeat.
An ineffable joy suffused me as I beheld
Bo!jofggbcmf!kpz!tvggvtfe!nf!bt!J!cfifme
the wonders of modern computing.
uif!xpoefst!pg!npefso!dpnqvujoh
Please excuse the slight confusion.
Note that one of the comments in Listing 6.2 suggests that changing ++ch to ch+1 has an interesting effect. Can you deduce what it will be? If not, try it out and then see if you can explain what’s happening. (Hint: Think about how cout handles different types.)
Formatting if else Statements
Keep in mind that the two alternatives in an if else statement must be single statements. If you need more than one statement, you must use braces to collect them into a single block statement. Unlike some languages, such as BASIC and FORTRAN, C++ does not automatically consider everything between if and else a block, so you have to use braces to make the statements a block. The following code, for example, produces a compiler error:
if (ch == 'Z')
zorro++; // if ends here
cout << "Another Zorro candidate\n";
else // wrong
dull++;
cout << "Not a Zorro candidate\n";
The compiler sees it as a simple if statement that ends with the zorro++; statement.
Then there is a cout statement. So far, so good. But then there is what the compiler perceives as an unattached else, and that is flagged as a syntax error.
You add braces to group statements into a single statement block:
if (ch == 'Z')
{ // if true block
zorro++;
cout << "Another Zorro candidate\n";
}
else
{ // if false block
dull++;
cout << "Not a Zorro candidate\n";
}
Because C++ is a free-form language, you can arrange the braces as you like, as long as they enclose the statements. The preceding code shows one popular format. Here’s another:
if (ch == 'Z') {
zorro++;
cout << "Another Zorro candidate\n";
}
else {
dull++;
cout << "Not a Zorro candidate\n";
}
The first form emphasizes the block structure for the statements, whereas the second form more closely ties the blocks to the keywords if and else. Either style is clear and consistent and should serve you well; however, you may encounter an instructor or employer with strong and specific views on the matter.
The if else if else Construction
Computer programs, like life, might present you with a choice of more than two selections. You can extend the C++ if else statement to meet such a need. As you’ve seen, the else should be followed by a single statement, which can be a block. Because an if else statement itself is a single statement, it can follow an else:
if (ch == 'A')
a_grade++; // alternative # 1
else
if (ch == 'B') // alternative # 2
b_grade++; // subalternative # 2a
else
soso++; // subalternative # 2b
If ch is not 'A', the program goes to the else. There, a second if else subdivides that alternative into two more choices. C++’s free formatting enables you to arrange these elements into an easier-to-read format:
if (ch == 'A')
a_grade++; // alternative # 1
else if (ch == 'B')
b_grade++; // alternative # 2
else
soso++; // alternative # 3
This looks like a new control structure—an if else if else structure. But actually it is one if else contained within a second. This revised format looks much cleaner, and it enables you to skim through the code to pick out the different alternatives. This entire construction still counts as one statement.
Listing 6.3 uses this preferred formatting to construct a modest quiz program.
Listing 6.3. ifelseif.cpp
// ifelseif.cpp -- using if else if else
#include