RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Intermediate
May 27, 2008

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.

Jacob Lund Fisker
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date