< previous page page_205 next page >

Page 205
if (divisor != 0)
    result = dividend / divisor;
else
{
    cout <<Division by zero is not allowed. << endl;
    result = 9999;
}
If the value of divisor is zero, the computer both prints the error message and sets the value of result to 9999 before continuing with whatever statement follows the If statement.
Blocks can be used in both branches of an If-Then-Else. For example:
if (divisor != 0)
{
    result = dividend / divisor;
    cout << Division performed. << endl;
}
else
{
    cout << Division by zero is not allowed. << endl;
    result = 9999;
}
When you use blocks in an If statement, there's a rule of C++ syntax to remember: Never use a semicolon after the right brace of a block. Semicolons are used only to terminate simple statements such as assignment statements, input statements, and output statements. If you look at the examples above, you won't see a semicolon after the right brace that signals the end of each block.
MATTERS OF STYLE
Braces and Blocks
C++ programmers use different styles when it comes to locating the left brace of a block. The style we use puts the left and right braces directly below the words if and else, each brace on its own line:

(text box continues on next page)

 
< previous page page_205 next page >