Search code examples
ioscobjective-csyntaxcomma-operator

Comma in Objective-C


I've just seen this in another question and thought the comma must be a typo

[controller release], controller = nil; 

I'm using ARC so didn't use release, but I tested this myself the following code and found that it compiled and ran fine.

NSObject *a = [NSObject new];
[a copy], a=nil;

I was under the impression that the comma was only used for separating lists and multiple assignments of the same type:

NSArray *a = @[@"1", @"two", /*etc*/]; 
int a, b, c, d;

Actual Question:

Is it as simple as: The comma can be used to separate commands? Are there any other rules?


Solution

  • The comma operator is a C-language construct.

    From Wikipedia:

    In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type). The comma operator has the lowest precedence of any C operator, and acts as a sequence point. The use of the comma token as an operator is distinct from its use in function calls and definitions, variable declarations, enum declarations, and similar constructs, where it acts as a separator.