In Objective-C, what does a comma do when used as a statement separator?

前端 未结 3 1262
春和景丽
春和景丽 2021-02-12 16:22

I am looking though some source code from a third party and am repeatedly seeing a syntax that is new to me. Basically they are separating statements with commas instead of semi

相关标签:
3条回答
  • 2021-02-12 17:02

    These are comma separated expressions and are evaluated from left to right, with the result of the entire expression being the last expression evaluated.

    0 讨论(0)
  • 2021-02-12 17:17

    As in C and C++, the comma operator computes the thing on its left side and then computes the thing on the right; the overall value of the expression is the value of the right side. Basically, this lets a single expression do two things (the one on the left side being presumably for side effects such as a method call or assignment). Yes, the syntax is somewhat ambiguous with that used in function calls and variable declarations.

    I prefer to use an honest block containing multiple statements where possible. Longer, but ultimately cleaner. Easier to debug too.

    0 讨论(0)
  • 2021-02-12 17:20

    This is one of my favorite "features" of C, ObjC, etc…

    Understanding this operator unlocks all sorts of possibilities for jQuery-like.chain-able.commands, and a more concise (thoug-some-would-argue-less-readable) expression of MANY common idioms.. For example...

    -(id)init { 
         return self != super.init ? nil : [self setProperty:@"EPIC"], 
         NSLog(@"One line inits are: %@.", _property), self;        }
    

    LOG ➜ One line inits are: EPIC.

    0 讨论(0)
提交回复
热议问题