c++parameterslanguage-lawyerorder-of-execution

What is the order of evaluation for function arguments?


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?


Solution

  • 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