== Operator and operands

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

Evaluated value == 1

1 == evaluated value

in terms of the compiler execution


Solution 1:

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.

Solution 2:

It depends on the programming language.

In Ruby, Smalltalk, Self, Newspeak, Ioke and many other single-dispatch object-oriented programming languages, a == b is actually a message send. In Ruby, for example, it is equivalent to a.==(b). What this means, is that when you write a == b, then the method == in the class of a is executed, but when you write b == a, then the method in the class of b is executed. So, it's obviously not the same thing:

class A; def ==(other) false end; end
class B; def ==(other) true  end; end

a, b = A.new, B.new

p a == b # => false
p b == a # => true

Solution 3:

No, but the latter syntax will give you a compiler error if you accidentally type

if (1 = evaluatedValue)

Note that today any decent compiler will warn you if you write

if (evaluatedValue = 1)

so it is mostly relevant for historical reasons.