Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in the two ways of checking equality i==0 vs 0==i in C++

Tags:

c++

I am going through a huge code-base in C++. The author has used 0==i syntax for checking equality. I have been coding in C++ for quite some years now; I have always used i==0 syntax.

Does the former have any advantages over the latter? Or is it just personal preference?

like image 844
Sonu Mishra Avatar asked Nov 28 '22 06:11

Sonu Mishra


2 Answers

0==i is called a "yoda conditional". It is most certainly a personal preference, but it does have an advantage.

It was used in the dark ages by mystical knights of the realm who lacked the modern technology to tell them when they'd written 0=i by mistake.

A compiler will reject an accidental 0=i, but it'll accept an accidental i=0.

This convention was phased out after the war of 1672. Contemporary shamans try to write code that makes sense to other shamans (also pixies, elves and humans), and instead use compilers written in this millennium (also, their eyes) to avoid such mistakes.

like image 183
Lightness Races in Orbit Avatar answered Nov 30 '22 20:11

Lightness Races in Orbit


The former has the advantage that it prevents the programmer from accidentally leaving out an equals sign.

if (i = 0)

The above is legal, and sets i to zero, and is false (since zero is considered false).

if (0 = i)

The above is illegal in all contexts.

Today, most compilers will warn about if (i = 0), but it is not a requirement, and they didn't always do so.

like image 35
md5i Avatar answered Nov 30 '22 21:11

md5i