C ++, rules for evaluating operands of ternary operators

Suppose I have the 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 seems that generate is called independently of R.empty() . Is this standard behavior?

+5
source share
1 answer

From clause 5.16 / 1 of the C ++ 11 standard:

Group conditional expressions from right to left. The first expression is contextually converted to bool (section 4). It is evaluated and, if true, the result of the conditional expression is the value of the second expression, otherwise, the third expression. Only one of the second and third expressions is evaluated . Each calculation of the value and side effect associated with the first expression are sequenced before each calculation of the value and side effect associated with the second or third expression.

+12
source

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


All Articles