Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary operator without second operand [duplicate]

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)?

like image 757
YSC Avatar asked Jan 08 '16 14:01

YSC


People also ask

Can ternary operator have 3 conditions?

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.

How many operands are needed for ternary operators?

The conditional operator (? :) is a ternary operator (it takes three operands).

Can ternary operator have two conditions?

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.

What are the three arguments of a ternary operator?

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.


2 Answers

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
like image 110
TartanLlama Avatar answered Oct 12 '22 23:10

TartanLlama


The ternary operator with omitted middle operand:

const char* str = opt ?: "";

is a GNU extension it's not standard C++.

like image 28
101010 Avatar answered Oct 12 '22 21:10

101010