views:

123

answers:

3

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 initializing your own classes? Apple documentation uses the former one (for example here), which style I'm actually using now.

+2  A: 

"An assignment expression has the value of the left operand after the assignment" (C99), so either way it has the value of variable, as you put it. The extra parentheses make no difference (except possibly for warnings).

Matthew Flaschen
+5  A: 

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.

quixoto
Thanx for clarifying what the expression does - and why I thought there has to be additional parenthesis! Now I recall getting such compiler warnings in other environments and adding second parenthesis (after checking expression really did what I wanted, of course).
JOM
+3  A: 

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) 
JeremyP
Good reminder about precedence!
JOM