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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With