2008 07 08Comma Trick
When failing, functions like
NSXMLDocument
's initWithContentsOfURL:options:error:
give more information via NSError
than a BOOL
. And you end up with code looking like that …
// Log and return if (error) { // Somehow display the error NSLog(@"MyFunction failed with error: %@", error); // And return from our function return NO; }
… opening a brace just to handle the error. This can be compacted with :
// Log and return if (error) return NSLog(@"MyFunction failed with error: %@", error), NO;
The comma operator evaluates expressions (standard arithmetic, function calls, etc. but NOT statements : while, if, …) and returns the value of the last one.
-
1, 2, 3
yields 3 -
fn(), NO
calls fn and yields NO -
fn1(), fn2(), fn3()
calls fn1, then fn2, then fn3, then yields the result of fn3
return
will evaluate its following expression (the comma-separated expression list) and return the value of the last one. This allows you to do one quick call to some logging function before returning.
return fn1(), fn2(), fn3(), fn4(), fn5()
will work ! ) but I think it's a nice thing to know.