Saturday, July 28, 2012

Avoiding Bugs: Using a Single = Instead of == in if

Solving bugs is great, but even better is avoiding those bugs in the first place.

One of the most annoying silly bugs, the ones you immediately curse yourself for not noticing,  is using a single = instead of == . The difference of course is that the first one is used to assign values while the second one is used to check for equality.

The way to avoid it is by always using the constant part of the equation as the left operand.
For example,
if (number = 5)
will compile and even return true. You would have to find this mistake during run-time. While
if (5 = number) 
will produce an immediate "left operand must be l-value" error during compilation allowing you to easily and quickly spot the bug.

Granted, this will only work if are comparing something to a constant and not if you have two variables and it also seems a bit unnatural to place the constant on the left. But in my opinion it is better to avoid the bug while still writing easily readable code than to write code which will look natural in everyone's eyes.

No comments:

Post a Comment