views:

279

answers:

4

I have been programming iPhone SDK for around 6 months but am a bit confused about a couple of things...one of which I am asking here:

Why are the following considered different?

if (varOrObject == nil)
{

}

vs

if (nil == varOrObject)
{

}

Coming from a perl background this is confusing to me...

Can someone please explain why one of the two (the second) would be true whereas the first would not if the two routines are placed one after the other within code. varOrObject would not have changed between the two if statements.

There is no specific code this is happening in, just that I have read in a lot of places that the two statements are different, but not why.

Thanks in advance.

+2  A: 

They are exactly the same, it is just a style difference. One would never be true if the other is false.

Jason Coco
+7  A: 

They are the same. What you have read is probably talking about if you mistakenly write == as =, the former will assign the value to the variable and the if condition will be false, while the latter would be a compile time error:

if (variable = nil) // assigns nil to variable, not an error.

if (nil = variable) // compile time error

The latter gives you the chance to correct the mistake at compile time.

Mehrdad Afshari
GCC 4.2 catches this at compile time with a warning.
kubi
A: 

if it's a recommendation that you use the latter, it's because the second is easier to catch if you accidentally type =. otherwise, they are identical and your book is wrong.

sreservoir
+3  A: 

They might be different if you are using Objective-C++ and you were overriding the '==' operator for the object.

Vagrant