Yoda Notation

What is your preferred comparison (==) style?

Yoda Notation

Consider the following C code. Which style do you prefer?

if ( x == 5 )
//...

//OR

if ( 5 == x )
//...

Both if statements have the same meaning exactly unless you forget to put a single = character! In C, you are allowed to do an assignment in the condition part (inside) of an if statement. Let's assume that we write = instead of == accidentally. The following code is also valid.

if ( x = 5 )
//...

According to the rules of C, the value generated by the assignment operator is the value assigned to the left operand, which is 5 (if x is wide enough (most probably) to hold the value 5) in this case. The equivalent if statement is given below.

if ( 5 )

Oops! We create an always-true if statement. Now, consider that the left and the right operands become 5 and x, respectively, and we do the same mistake:

//The line below has a syntax error.
if ( 5 = x )

We get a compilation error because the expression, 5 = x, is invalid in C. The left operand of the assignment operator must be an lvalue expression (a modifiable lvalue expression, to be more exact) but 5 is an rvalue expression. The compiler can catch this error.

💡
Learn more about lvalue and rvalue (value categories): Value categories

If we compare an lvalue expression (like constants as in this case) with an rvalue expression, making the lvalue expression left operand of the equality operator, ==, is a good practice. In other words, writing if (<rvalue> ==<lvalue>) ✅ instead of if (<lvalue> == <rvalue>) ❌ can save our lives. However, if both sides are lvalue expressions, like comparing two variables, we can not avoid this mistake easily. In that case, if you are lucky, your compiler may generate a warning. Creating if statements with if (<rvalue> == <lvalue>) style is also known as Yoda Notation or Yoda Conditions in programming.

In summary, put constants to the left of ==.

This is also recommended by Embedded C Coding Standard - Barr Group (8.6 Equivalence Tests) and by sonarqube (RSPEC-1772).

P.S. I would like to thank ANIL TIRLIOĞLU for reminding the name of the style: Yoda!

Further Read