6.10 Answers to Chapter Questions

I l @ ve RuBoard

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

I l @ ve RuBoard


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net