?: in Objective-C

In this iOS tutorial, is there a line of code with ? followed by : In the context of the code comment, I thought it was a kind of triple operation, but this is clearly not the syntax for the ternary operator. Is there a name for what happens in this code with ?: ?

 // Initialize the list of weather items if it doesn't exist NSMutableArray *array = self.xmlWeather[@"weather"] ?: [NSMutableArray array]; 
+6
source share
1 answer

This is aa gcc extension :

6.7 Symbols with operands omitted

The middle operand of the conditional expression may be omitted. Then, if the first operand is nonzero, its value is the value of the conditional expression.

Therefore, the expression

 x ? : y 

has value x if it is nonzero; otherwise, y .

This example is absolutely equivalent.

 x ? x : y 

In this simple case, the ability to omit the middle operand is not particularly useful. When it becomes useful, it is when the first operand does or can (if it is a macro argument) contains a side effect. Then repeating the operand in the middle will perform a side effect twice. Lowering the middle operand uses the value already calculated without the unwanted translation effects.

+23
source

Source: https://habr.com/ru/post/971664/


All Articles