Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if (self = [super init]) vs. if ((self = [super init]))

Tags:

Was just doing a code review and started to wonder:

I thought if (self = [super init]) checks whether assigning return value of [super init] to variable self was successful or not (value of operation). Thus (self = nil) would actually be TRUE.

I thought if ((self = [super init])) checks what is the value of self after assignment (value of variable). Thus ((self = nil)) would be FALSE.

Which one is the correct way to use when initialising your own classes? Apple documentation uses the former one (for example here), which style I'm actually using now.

like image 600
JOM Avatar asked Jun 17 '10 05:06

JOM


2 Answers

They both do the same thing. The thing that the if evaluates is the value of the expression inside it, which is the assigned value in an assignment. So when self is not nil, you proceed into the if block.

The second form throws parens around it to silence any potential compiler warnings about assignments inside conditionals, which is generally bad practice and possibly a typo. But this is idiomatic Objective-C, so it's fine to do it the first way.

like image 132
Ben Zotto Avatar answered Sep 21 '22 17:09

Ben Zotto


As others have said the parentheses don't matter in this case. Where they do matter is if you explicitly check against nil:

if (self = [super init] != nil) // wrong!  if ((self = [super init]) != nil) // right 

!= has higher precedence than = so in the first case you assign the boolean result of [super init] != nil (probably true) to self and then does the test for the if.

Personally, I don't care for either but prefer to do the assignment explicitly outside of the test. This is a reflection of my programming background that has led me to the belief that booleans are a different type from integers and pointers and that assignments are not expressions, even though, in the case of the C implementation, I am wrong.

self = [super init]; if (self != nil)  
like image 25
JeremyP Avatar answered Sep 24 '22 17:09

JeremyP