Question

I found a way to assign a value like this:

NSString *result = [self string] ?: @"none";

If [self string] return a value that not equals to nil, result will be that returning value, else, be @"none". Just like the or operator in Python.

I tested for several cases, It works fine. Like:

int a = 10 ?: 0; // a is 10
int a = 0 ?: 5; // a is 5
NSString *str = @"abc" ?: 10; // warning: incompatible pointer. It has type checking?

But I couldn't find any relative documents or information about this syntax. So I wondered why it works. Can somebody explain it?

Was it helpful?

Solution

This is a GNU extension to C, documented here. Note that it evaluates the expression only once, and reuses the result (useful when your expression has side effects). clang includes it but I can't find any related documentation on that.


Edit: Here's the class reference for the implementation with LLVM: http://clang.llvm.org/doxygen/classclang_1_1BinaryConditionalOperator.html

Note that is says:

BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle operand to be omitted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top