What follows are 10 of the more important things to keep in mind if you want to write polished, professional C++ code that is easy to maintain and less likely to need debugging—so I am actually more exacting here in this article than I sometimes am in my book, C++ Without Fear, Second Edition.
These guidelines are in no particular order (sorry David Letterman), except that the earlier items are addressed more to mistakes that beginners have trouble with.
#1: Don’t Confuse Assign (=) with Test-for-Equality (==).
This one is elementary, although it might have baffled Sherlock Holmes. The following looks innocent and would compile and run just fine if C++ were more like BASIC:
if (a = b)
cout << "a is equal to b.";
Because this looks so innocent, it creates logic errors requiring hours to track down within a large program unless you’re on the lookout for it. (So when a program requires debugging, this is the first thing I look for.) In C and C++, the following is not a test for equality:
a = b
What this does, of course, is assign the value of b to a and then evaluate to the value assigned.
The problem is that a = b does not generally evaluate to a reasonable true/false condition—with one major exception I’ll mention later. But in C and C++, any numeric value can be used as a condition for “if” or “while.
Assume that a and b are set to 0. The effect of the previously-shown if statement is to place the value of b into a; then the expression a = b evaluates to 0. The value 0 equates to false. Consequently, a and b are equal, but exactly the wrong thing gets printed:
if (a = b) // THIS ENSURES a AND b ARE EQUAL...
cout << "a and b are equal.";
else
cout << "a and b are not equal."; // BUT THIS GETS PRINTED!
The solution, of course, is to use test-for-equality when that’s what you want. Note the use of double equal signs (==). This is correct inside a condition.
// CORRECT VERSION:
if (a == b)
cout << "a and b are equal.";
#2: Do Get Rid of “Magic Numbers”
Read more: InformIT
0 comments:
Post a Comment