Jann
Jann

Reputation: 2213

iPhone SDK: Please explain why "nil ==" is different than "== nil"

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.

Upvotes: 1

Views: 688

Answers (5)

Konrad Höffner
Konrad Höffner

Reputation: 12207

They can only be different if the "==" - Operator is overloaded. Let's say someone redefines "==" for a list, so that the content of two lists is checked rather than the memory adress (like "equals() in Java). Now the same person could theoretically define that "emptyList == NULL".

Now (emptyList==NULL) would be true but (NULL==emptyList) would still be false.

Upvotes: 0

Vagrant
Vagrant

Reputation: 1716

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

Upvotes: 4

muhmuhten
muhmuhten

Reputation: 3341

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.

Upvotes: 0

Mehrdad Afshari
Mehrdad Afshari

Reputation: 421978

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.

Upvotes: 9

Jason Coco
Jason Coco

Reputation: 78353

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

Upvotes: 2

Related Questions