This is a two legged question: one for C and one for C++.
What the C and C++ standards have to say about the following use of the ternary (?:
) operator:
const char* opt = /* possible NULL pointer */;
const char* str = opt ?: "";
When did it became legal? Is it a compiler extension? What are the requirements on the first operand (implicitly convertible to bool
/int
)?
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
The conditional operator (? :) is a ternary operator (it takes three operands).
In the above syntax, we have tested 2 conditions in a single statement using the ternary operator. In the syntax, if condition1 is incorrect then Expression3 will be executed else if condition1 is correct then the output depends on the condition2.
The ternary operator take three arguments: The first is a comparison argument. The second is the result upon a true comparison. The third is the result upon a false comparison.
GCC provides this as an extension. This is not in the C++ standard.
The semantics are that if the condition is nonzero, the value of the expression is that of the condition.
The implicit requirement is that the condition must be type-compatible with the third operand, i.e. one can be converted to the other following the usual conditional operator rules.
It's important to note that if the condition is computed from a function with side effects, the value will not be recomputed with this extension:
opt() ?: ""; //opt called once
opt() ? opt() : ""; //opt called twice
The ternary operator with omitted middle operand:
const char* str = opt ?: "";
is a GNU extension it's not standard C++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With