Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 semicolons. It compiles and works, but I don't understand what it is doing. It looks like so

if(url)[url release], url = nil;

and they also use it without the if sometimes

[url release], url = nil;

What's going on here?

like image 514
Joe Cannatti Avatar asked Apr 06 '10 14:04

Joe Cannatti


People also ask

What does a comma do in C?

The comma operator in c comes with the lowest precedence in the C language. The comma operator is basically a binary operator that initially operates the first available operand, discards the obtained result from it, evaluates the operands present after this, and then returns the result/value accordingly.

What does comma operator do?

The comma operator ( , ) evaluates each of its operands (from left to right) and returns the value of the last operand. This lets you create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions.

Can we use comma in if statement?

Use a comma after the if-clause when the if-clause precedes the main clause. If I'd had time, I would have cleaned the house. If the main clause precedes the if-clause, no punctuation is necessary. I would have cleaned the house if I'd had time.

How do commas work in Python?

On the left-hand side of an assignment, the comma indicates that sequence unpacking should be performed according to the rules you quoted: a will be assigned the first element of the tuple, b the second.


2 Answers

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.

like image 114
Donal Fellows Avatar answered Oct 24 '22 13:10

Donal Fellows


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

like image 33
diederikh Avatar answered Oct 24 '22 11:10

diederikh