Search code examples
c++coding-style

Any differences between ( var > x) and ( x < var)?


I have seen embedded programming use conditions in reverse order like literal on the left side instead of right in conditional checks.

( var > 0) and ( 0 < var) 

Is there a reason for this ? or its just a one of coding style ?

Thanks

EDIT: Thanks everyone for answering and clearing my doubt.


Solution

  • They are equivalent. The only difference could be if operator</> is overloaded, and these overloads have difference meaning (discouraged, though).

    I've seen people doing this for the equality operator, to avoid using assigment mistakely. So instead of this:

    if (a==0) ...
    

    Mistakenly this is written:

    if (a=0) ... // compiles, and not what we wanted, a assigned to zero, and "if" never taken
    

    If we have used reversed comparison instead:

    if (0==a) ...
    

    Then the wrong version doesn't compile:

    if (0=a) ... // doesn't compile
    

    But this is not too important today, as most compilers will warn you for if (a=0).

    As Max Langhof notes, this reversed condition is called Yoda conditions due to the order being different from the normal English one.