Sunday, November 05, 2006

Avoiding Unnecessary Bugs

A typo often made by even the most experienced programmers is placing an if (a = 1) statement where an if (a == 1) is meant. Instead of checking whether the value of variable a equals 1, the first statement will assign the value 1 to a, and the if will always be true. These kinds of bugs can be very hard to find but are easily avoided by simply adopting a different coding style. When you train yourself to turn around the elements of which the expressions are made up, the compiler will 'warn'you when you make this kind of typo.
if (1 == a)
if (NULL == fp)
. . .
By placing the constant first, the compiler will complain about you trying to assign a value to a constant as soon as you forget the second =.

No comments: