Objective-c – Is this ternary conditional ?: correct (Objective) C syntax

cconditional-operatorobjective cternary-operator

I didn't think this was possible but apparently in Objective C it is allowed:

int a = b ?: c;

So you see what they're doing here, they're leaving out the second part of the ternary expression, such that if b is nonzero, b is used as the second part.

It's clever but as far as I know this is against K&R C, and probably ANSI C.

If not, I've been missing out of a terribly clever syntax trick for years…alas!

Update:
It is gcc.

Best Answer

From http://en.wikipedia.org/wiki/%3F%3A

A GNU extension to C allows omitting the second operand, and using implicitly the first operand as the second also:

a = x ? : y;

The expression is equivalent to

a = x ? x : y;

except that if x is an expression, it is evaluated only once. The difference is significant if evaluating the expression has side effects.