Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++, ternary operator operand evaluation rules

Tags:

c++

Lets say i have following code:

std::vector<T> R;
if (condition) R = generate();
...
for (int i = 0; i < N; ++i) {
    const auto &r = (R.empty() ? generate() : R);
}

It appears that generate is called regardless of R.empty(). Is that standard behavior?

like image 789
Anycorn Avatar asked Feb 07 '13 23:02

Anycorn


People also ask

How do you evaluate 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.

How do you write 3 conditions in a ternary operator?

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?

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

What is the correct syntax of ternary operator in C?

Example: C Ternary Operator printf("You can vote") - expression1 that is executed if condition is true. printf("You cannot vote") - expression2 that is executed if condition is false.


1 Answers

From Paragraph 5.16/1 of the C++ 11 Standard:

Conditional expressions group right-to-left. The first expression is contextually converted to bool (Clause 4). It is evaluated and if it is true, the result of the conditional expression is the value of the second expression, otherwise that of the third expression. Only one of the second and third expressions is evaluated. Every value computation and side effect associated with the first expression is sequenced before every value computation and side effect associated with the second or third expression.

like image 50
Andy Prowl Avatar answered Oct 08 '22 02:10

Andy Prowl