Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the ?: operator

In an example of Objective-C code I found this operator

self.itemViews[@(0)] ?: [self.dataSource slidingViewStack:self viewForItemAtIndex:0 reusingView:[self dequeueItemView]];

The code does compile under Apple LLVM 4.2.

The only thing I came across was in being a vector operator, but I don't think Objective-C, and for that matter C, has vector operators. So can someone please give reference and or documentation of this operator.

like image 565
NebulaFox Avatar asked Jul 31 '13 09:07

NebulaFox


2 Answers

?: is the C conditional operator.

a ? b : c

yields b value if a is different than 0 and c if a is equal to 0.

A GNU extension (Conditional with Omitted Operand) allows to use it with no second operand:

 x ? : y 

is equivalent to

 x ? x : y
like image 81
ouah Avatar answered Oct 23 '22 06:10

ouah


Are you familiar with the Ternary operator? Usually seen in the style:

test ? result_a : result_b;

All that has happened here is that the first branch has not been given so nothing will happen in the positive case. Similar to the following:

test ?: result_b;

Due to the way that C is evaluated, this will return result_b if test is untruthy, otherwise it will return test.

In the example that you have given - if the view is missing, it falls back to checking the datasource to provide a replacement value.

like image 43
Aaron Cronin Avatar answered Oct 23 '22 06:10

Aaron Cronin