Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary operator assignment in Objective-C [duplicate]

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?

like image 704
Steven Mok Avatar asked Sep 03 '25 10:09

Steven Mok


1 Answers

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.

like image 139
sidyll Avatar answered Sep 05 '25 15:09

sidyll