With C++ there are only a few operators that guarantee the evaluation order
operator &&
evaluates left operand first and if the value is logically false
then it avoids evaluating the right operand. Typical use is for example if (x > 0 && k/x < limit) ...
that avoids division by zero problems.
operator ||
evaluates left operand first and if the value is logically true
then it avoids evaluating the right operand. For example if (overwrite_files || confirm("File existing, overwrite?")) ...
will not ask confirmation when the flag overwrite_files
is set.
operator ,
evaluates left operand first and then right operand anyway, returning the value of right operand. This operator is not used very often. Note that commas between parameters in a function call are not comma operators and the order of evaluation is not guaranteed.
The ternary operator x?y:z
evaluates x
first, and then depending on the logical value of the result evaluates either only y
or only z
.
For all other operators the order of evaluation is not specified.
The situation is actually worse because it's not that the order is not specified, but that there is not even an "order" for the expression at all, and for example in
std::cout << f() << g() << x(k(), h());
it's possible that functions will be called in the order h-g-k-x-f
(this is a bit disturbing because the mental model of <<
operator conveys somehow the idea of sequentiality but in reality respects the sequence only in the order results are put on the stream and not in the order the results are computed).
Obviously the value dependencies in the expression may introduce some order guarantee; for example in the above expression it's guaranteed that both k()
and h()
will be called before x(...)
because the return values from both are needed to call x
(C++ is not lazy).
Note also that the guarantees for &&
, ||
and ,
are valid only for predefined operators. If you overload those operators for your types they will be in that case like normal function calls and the order of evaluation of the operands will be unspecified.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…