Get into the Habit of Preventing Bugs in if Statements

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.

See also  Monetize TikTok For Your Business

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist