Search code examples
language-agnosticoperatorsequality

Should I write (x == 1) or (1 == x) to check if a value is equal to 1?


I want to check whether a value is equal to 1. Is there any difference in the following lines of code

x == 1
1 == x

... in terms of the compiler execution?


Solution

  • In most languages it's the same thing.

    People often do 1 == evaluated value because 1 is not an lvalue. Meaning that you can't accidentally do an assignment.

    Example:

    if(x = 6)//bug, but no compiling error
    {
    }
    

    Instead you could force a compiling error instead of a bug:

    if(6 = x)//compiling error
    {
    }
    

    Now if x is not of int type, and you're using something like C++, then the user could have created an operator==(int) override which takes this question to a new meaning. The 6 == x wouldn't compile in that case but the x == 6 would.