6.10 Answers to Chapter Questions
Answer 6-1: This program illustrates one of the
most common and most frustrating errors a beginning C++ programmer
makes. The problem is that C++ allows assignment statements inside
if conditionals. The statement:
if (balance_owed = 0)
uses a single equal sign instead of the double equal. C++ will assign
balance_owed the value 0 and then test the result
(which is zero). If the result were nonzero (true), the if clause would be executed. Since the result
is zero (false), the else clause is
executed and the program prints the wrong answer.
The statement
if (balance_owed = 0)
is equivalent to
balance_owed = 0;
if (balanced_owed != 0)
The statement should be written:
if (balance_owed == 0)
I once taught a course in C programming. One day about a month after
the course had ended, I saw one of my former students on the street.
He greeted me and said, "Steve, I have to tell you
the truth. During the class I thought you were going a bit overboard
on this single equal versus double equal bug, until now. You see, I
just wrote the first C program for my job, and guess what mistake I
made."
One trick many programmers use is to put the constant first in any
== statement. For example:
if (0 == balanced_owed)
This way, if the programmer makes a mistake and puts in
= instead of ==, the result is:
if (0 = balanced_owed)
which causes a compiler error. (You can't assign
balance_owed to 0.)
|