tags:

views:

165

answers:

3

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?

+3  A: 

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.

Donal Fellows
I totally agree with Donal, especially for this kind of thing. Not using a block here is just lazy and harder to read.
Jason Coco
Thanks. I'll be sure to avoid using it for this purpose in my own code. I'm glad I know you can do this now though. Might be useful elsewhere.
Joe Cannatti
A: 

This is just a combined assignment statement.

Does this look familiar to you?

int a, b = 1;

Stefan Kendall
That's an initializer list, which is a different thing entirely. A function argument list is also a different thing. This is the C comma operator.
David Thornley
+2  A: 

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

Diederik Hoogenboom