The Otherwise Operator

By: Jeremy W. Sherman. Published: . Categories: c gnu-c obj-c syntax.

GNU C adds a binary operator ?:. Use it to fall back to a default value when a nil check fails:

id target = [self.delegate target] ?: [self.class defaultTarget];

The GCC docs present the binary ?: operator as eliding a repeated first term when using the ternary conditional operator, so

x ? x : y

can now be written

x ?   : y

and have the same effect as the full form, save that the first term, x, is only evaluated once.

From this point of view, the binary ?: exists to avoid unwanted side effects:

int z = (x++) ? (x++) : y;  // bad news
int w = (x++) ?       : y;  // OK!

But thinking of ?: as a special-purpose variant of the ternary operator misses its true calling: cleaning up nil and NULL checks. It compacts several lines of code:

id target = [self.delegate target];
if (!target) {
    target = [self.class defaultTarget];

down to a one-liner:

id target = [self.delegate target] ?: [self.class defaultTarget];

So: The ”otherwise” – or ”if nil then” – operator: ?:. Use it.