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 ...

Get C++ Primer Plus now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.