"IF" argument evaluation order?
With C++ there are only a few operators that guarantee the evaluation order
operator &&
evaluates left operand first and if the value is logicallyfalse
then it avoids evaluating the right operand. Typical use is for exampleif (x > 0 && k/x < limit) ...
that avoids division by zero problems.operator ||
evaluates left operand first and if the value is logicallytrue
then it avoids evaluating the right operand. For exampleif (overwrite_files || confirm("File existing, overwrite?")) ...
will not ask confirmation when the flagoverwrite_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
evaluatesx
first, and then depending on the logical value of the result evaluates either onlyy
or onlyz
.
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.
Changes since C++17
C++17 introduced some extra ad-hoc specific guarantees about evaluation order (for example in the left-shift operator <<
). For all the details see https://stackoverflow.com/a/38501596/320726
The evaluation order is specified by the standard and is left-to-right
. The left-most expression will always be evaluated first with the &&
clause.
If you want b
to be evaluated first:
if(b && a)
{
//do something
}
If both arguments are methods and you want both of them to be evaluated regardless of their result:
bool rb = b();
bool ra = a();
if ( ra && rb )
{
//do something
}