简体   繁体   中英

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

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.

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.

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) 

"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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM