rvar == lvar, instead of lvar == rvar?

Mostly you will write code like this :

int i = 5;
if( i == 6 )

However, sometimes you will see code lines like this.

if( 6 == i )

[Fig.1] Real World Example of rvar == lvar

It will look odd. However, why do S/W engineers who have long experience in programming write code like that way?
Have you ever been curious about it?

The reason is to prevent any unintended bug introduced by typo.
if you put ivar in the left side of equality comparison, you can write code like this.

if( i = 6 )

Then the compiler will not catch it and just assign 6 to i. Then because it is non-zero, it will be evaluated to “true”.

However, if you write the ivar on the right side of a literal like this and unintentionally make a typo,

if( 6 = i )

the compiler can catch it, because it can’t assign i to 6.

Quite smart, isn’t it?

[Fig.2] Mixed Use


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: