if else
StatementsKeep 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
";
else // wrong
dull++;
cout << "Not a Zorro candidate
";
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
";
}
else
{ // if false block
dull++;
cout << "Not a Zorro candidate
";
}
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
";
}
else {
dull++;
cout << "Not a Zorro candidate
";
}
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.
3.146.221.144