|
|
|
|
|
|
|
result = line17 - line23;
if (result <0.0)
{
cout < Check box 24A << endl;
result = 0.0;
}
line24 = result; |
|
|
|
|
|
|
|
|
This code does exactly what the tax form says it should. It computes the result of subtracting line 23 from line 17. Then it looks to see if result is less than zero. If it is, the fragment prints a message telling the user to check box 24A and then sets result to zero. Finally, the calculated result (or zero, if the result is less than zero) is stored into a variable named line24. |
|
|
|
|
|
|
|
|
What happens if we leave out the left and right braces in the code fragment above? Let's look at it: |
|
|
|
|
|
|
|
|
result = line17 - line23; // Incorrect version
if (result < 0.0)
cout << Check box 24A << endl;
result =0.0;
line24 = result; |
|
|
|
|
|
|
|
|
Despite the way we have indented the code, the compiler takes the thenclause to be a single statementthe output statement. If result is less than zero, the computer executes the output statement, then sets result to zero, and then stores result into line24. So far, so good. But if result is initially greater than or equal to zero, the computer skips the then-clause and proceeds to the statement following the If statementthe assignment statement that sets result to zero. The unhappy outcome is that result ends up as zero no matter what its initial value was! The moral here is not to rely on indentation alone; you can't fool the compiler. If you want a compound statement for a then-or else-clause, you must include the left and right braces. |
|
|
|
|
|
|
|
|
Earlier we warned against confusing the = operator and the == operator. Here is an example of a mistake that every C++ programmer is guaranteed to make at least once in his or her career: |
|
|
|
|
|
|
|
|
cin >> n;
if (n = 3) // Wrong
cout << n equals 3;
else
cout << n doesn't equal 3; |
|
|
|
|
|