Order of evaluation in C++ function parameters

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.


No, there's no such guarantee. It's unspecified according to the C++ standard.

Bjarne Stroustrup also says it explicitly in "The C++ Programming Language" 3rd edition section 6.2.2, with some reasoning:

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 is also unspecified, i.e.

int x = f(2) + g(3);   // unspecified whether f() or g() is called first

C++17 specifies evaluation order for operators that was unspecified until C++17. See the question What are the evaluation order guarantees introduced by C++17? But note your expression

foo(bar(), baz())

has still unspecified evaluation order.

Tags:

C++

Standards