5.9. Confusing the Equality (==) and Assignment (=) Operators

There’s one error that C++ programmers, no matter how experienced, tend to make so frequently that we feel it requires a separate section. That error is accidentally swapping the operators == (equality) and = (assignment). What makes this so damaging is that it ordinarily does not cause syntax errors—statements with these errors tend to compile correctly and the programs run to completion, often generating incorrect results through runtime logic errors. Some compilers issue a warning when = is used in a context where == is expected.

Two aspects of C++ contribute to these problems. One is that any expression that produces a value can be used as a condition—if the value of the expression is zero, it’s treated as false, and if the value is nonzero, it’s treated as true. The second is that assignments produce a value—namely, the value assigned to the variable on the left side of the assignment operator. For example, suppose we intend to write

if ( payCode == 4 ) // good
   cout << "You get a bonus!" << endl;

but we accidentally write

if ( payCode = 4 ) // bad
   cout << "You get a bonus!" << endl;

The first if statement properly awards a bonus to the person whose payCode is equal to 4. The second one—which contains the error—evaluates the assignment expression in the if condition as the value 4. Any nonzero value is interpreted as true, so this condition always evaluates as true and the person always receives a bonus regardless of what the actual paycode is! Even worse, the paycode has been modified when it was only supposed to be examined!


Image Error-Prevention Tip 5.4

Programmers normally write conditions such as x == 7 with the variable name on the left and the constant on the right. By placing the constant on the left, as in 7 == x, you’ll be protected by the compiler if you accidentally replace the == operator with = . The compiler treats this as a compilation error, because you can’t change the value of a constant. This will prevent the potential devastation of a runtime logic error.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.136.119