Teaser

May the Force be with you


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

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

//OR

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

Both if statement have the same meaning exactly, unless you forget putting a single = character! In C, you are allowed doing an assignment in 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 the rules of C, the value generated by the assignment operator is the value assigned to 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 but 5 is an rvalue expression. 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 rvalue 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


Did you like it? Wanna give me a support? If yes then you may

Buy Me A Coffee