Get into the Habit of Preventing Bugs in if Statements

Unintentionally using = instead of == in an if statement can prove a nasty source of bugs. In the following code, myFunc is called if i equals 0:

if (i==0) myFunc(i);  

Now suppose that in your haste to meet a deadline, you accidentally wrote:

if (i=0) myFunc(i);

This code would still compile (unless i is a const), but in this case myFunc(i) would always be called, because i=0 is an assignment that always evaluates to true, which is not what you intended. If i is an iterator, even worse things might happen.

To avoid these disasters, get into the habit of writing your tests like this:

 if (0==i) ...

This is a perfectly valid?albeit somewhat odd-looking?way of writing tests.

Suppose you forget the == and write =? The code looks like this:

if (0=i) ...

The compiler catches the error correctly. Get in the habit of writing the number on the left hand side of the == rather than the usual right hand side.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: