Common pitfalls when using operators
As illustrated above, one of the pitfalls
when using operators is trying to get away without parentheses when you are even
the least bit uncertain about how an expression will evaluate (consult your
local C manual for the order of expression evaluation).
Another extremely common error looks like
this:
//: C03:Pitfall.cpp
// Operator mistakes
int main() {
int a = 1, b = 1;
while(a = b) {
// ....
}
} ///:~
The statement a = b will always
evaluate to true when b is non-zero. The variable
a is assigned to the value of b, and the value of b is also
produced by the operator =. In general, you want
to use the equivalence operator
== inside a conditional statement, not assignment. This one bites a lot
of programmers (however, some compilers will point out the problem to you, which
is helpful).
A similar problem is using bitwise
and and or instead of their logical counterparts. Bitwise
and and or use one of the characters (& or |),
while logical and and or use two (&& and
||). Just as with = and ==, it’s easy to just type
one character instead of two. A useful mnemonic device is to observe that
“Bits are smaller, so they don’t need as many characters in their
operators.”