views:

460

answers:

12

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

+2  A: 

It's the same thing

Sergio
That's wrong. I can think of at least 5 languages where that is not the case. And since I don't actually know that many languages, I would guess that there's probably a couple hundred more for which this is also the case.
Jörg W Mittag
Jörg W Mittag: just curious, can you give one example where (A == 5) is different from (5 == A)?
Sergio
+14  A: 

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.

Brian R. Bondy
I happen to think doing it that way is a crock, but you're right, that's why people do it that way.
Paul Tomblin
Agreed with Paul. Code is less readable that way. Some C++ compilers will issue a warning if you do this, and smartly, C# does not allow it.
rlbond
I have done it before, but mainly because I work on a huge project and it has some warnings we just can't seem to get the time to remove. So I'm afraid such an accidental assingment may happen one day. Or an accidental deletion of a single = char at a random spot.
Brian R. Bondy
"Code is less readable that way". Surely that just depends whether you're used to it? If you hate it then of course it's less readable, since you have a small conniption each time you see it. If you like it or don't care, then not so much.
Steve Jessop
"Less readable" depends on the rhs. When you use this because switch() is broken, then "if (CONST1 == x) ... else if (CONST2 == x)" is much more readable than the alternative.
Aaron Digulla
This is wrong. I can think of *at least* 5 languages, in which a == b and b == a are not the same.
Jörg W Mittag
@Jörg W Mittag: I corrected my answer so it doesn't imply that it applies to all languages. Thanks for the correction.
Brian R. Bondy
@Paul Tomblin: And in PHP you have if($value = someFunction()){ ... } AH!
SeanJA
@Steve Jessop: hard to understand are you sure it isn't? my case I rest.
David Lin
@davidlin: irrelevant to the question at hand. You're cunningly breaking English word order to demonstrate that there exist situations where order affects comprehension. Equality is a symmetric relation, you have not used any examples of symmetric relations. Obviously it makes a difference to comprehensibility for you - you find "6 == x" hard to understand. But that fact that I find your English text hard to understand does not mean that I find "6 == x" hard to understand.
Steve Jessop
Also, you've moved verbs to the end. I don't think anyone is proposing '6 x ==' (Reverse Polish) as a particularly intuitive syntax, although I suppose that if you're used to it (e.g. if you're an ancient calculator) then it's fine.
Steve Jessop
+4  A: 

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.

erikkallen
+5  A: 

Depends on the language.

Douglas Leeder
A: 
if value == 1
if 1 == value

Is exactly the same, but if you accidentally do

if value = 1
if 1 = value

The first one will work while the 2nd one will produce an error.

Ólafur Waage
A: 

They are the same. Some people prefer putting the 1 first, to void accidentally falling into the trap of typing

 evaluated value = 1

which could be painful if the value on the left hand side is assignable. This is a common "defensive" pattern in C, for instance.

unwind
+1  A: 

For this and similar questions can I suggest you find out for yourself by writing a little code, running it through your compiler and viewing the emitted asembler output.

For example, for the GNU compilers, you do this with the -S flag. For the VS compilers, the most convenient route is to run your test program in the debugger and then use the assembeler debugger view.

anon
Agree but he probably wanted to know why someone would do something so strange, knowing that they are actually the same, instead of if they are actually the same.
Brian R. Bondy
+1  A: 

Sometimes in C++ they do different things, if the evaluated value is a user type and operator== is defined. Badly.

But that's very rarely the reason anyone would choose one way around over the other: if operator== is not commutative/symmetric, including if the type of the value has a conversion from int, then you have A Problem that probably wants fixing rather than working around. Brian R. Bondy's answer, and others, are probably on the mark for why anyone worries about it in practice.

But the fact remains that even if operator== is commutative, the compiler might not do exactly the same thing in each case. It will (by definition) return the same result, but it might do things in a slightly different order, or whatever.

Steve Jessop
A: 

In C languages it's common to put the constant or magic number first so that if you forget one of the "=" of the equality check (==) then the compiler won't interpret this as an assignment.

In java, you cannot do an assignment within a boolean expression, and so for Java, it is irrelevant which order the equality operands are written in; The compiler should flag an error anyway.

Kurley
+2  A: 

In general, it hardly matters whether you use, Evaluated value == 1 OR 1 == evaluated value.

Use whichever appears more readable to you. I prefer if(Evaluated value == 1) because it looks more readable to me.

And again, I'd like to quote a well known scenario of string comparison in java. Consider a String str which you have to compare with say another string "SomeString".

str = getValueFromSomeRoutine();

Now at runtime, you are not sure if str would be NULL. So to avoid exception you'll write

if(str!=NULL)
{
   if(str.equals("SomeString")
   {
      //do stuff
    }
}

to avoid the outer null check you could just write

if ("SomeString".equals(str))
{
   //do stuff
}

Though this is less readable which again depends on the context, this saves you an extra if.

Chandan .
+3  A: 

In Prolog or Erlang, == is written = and is a unification rather than an assignment (you're asserting that the values are equal, rather then testing that they are equal or forcing them to be equal), so you can use it for an assertion if the left hand side is a constant, as explained here.

So X = 3 would unify the variable X and the value 3, whereas 3 = X would attempt to unify the constant 3 with the current value of X, and be equivalent of assert(x==3) in imperative languages.

Pete Kirkham
When you say "union" you mean "unification", I suppose?
starblue
+6  A: 

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
Jörg W Mittag
You can redefine operator==() in C++, too, but making it nonsymmetrical is probably a bad idea. Also see Pete Kirkham's answer citing Prolog and Erlang. You're up to eight languages where a==b is not necessarily the same as b==a.
David Thornley
I agree that having it non-symmetrical is a bad idea. However, in Ruby, there is no way to do that: == is a method that is always sent to the receiver. You could implement double-dispatch by hand (similar to the Visitor Pattern), and, indeed the numerical classes do that, but you can't enforce it.
Jörg W Mittag