If we have three functions (foo, bar, and baz) that are composed like so...
foo(bar(), baz())
Is there any guarantee by the C++ standard that bar will be evaluated before baz?
If we have three functions (foo, bar, and baz) that are composed like so...
foo(bar(), baz())
Is there any guarantee by the C++ standard that bar will be evaluated before baz?
No, there's no such guarantee. Bjarne Stroustrup says it explicitly in "The C++ Programming Language" 3rd edition section 6.2.2
He also gives a reason:
Better code can be generated in the absence of restrictions on expression evaluation order
Although technically this refers to an earlier part of the same section which says that the order of evaluation of parts of an expression are also undefined, i.e.
int x = f(2) + g(3); // udefined whether f() or g() is called first
There's no specified order for bar() and baz() - the only thing the Standard says is that they will both be evaluated before foo() is called. From the C++ Standard, section 5.2.2/8:
The order of evaluation of arguments is unspecified.
From [5.2.2] Function call,
The order of evaluation of arguments is unspecified. All side effects of argument expression evaluations take effect before the function is entered.
Therefore, there is no guarantee that bar()
will run before baz()
, only that bar()
and baz()
will be called before foo
.
Also note from [5] Expressions that:
except where noted [e.g. special rules for
&&
and||
], the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified.
so even if you were asking whether bar()
will run before baz()
in foo(bar() + baz())
, the order is still unspecified.