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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

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



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date