问题
In previous versions of the standard (C++03) the order of evaluation of parameters to a function call was unspecified.
Has this been changed in subsequent version of the standard (C++11 or C++14)?
i.e. Can we rely on a specific ordering (left to right) or not.
回答1:
No this has not changed but there is a very recent proposal to change this: N4228: Refining Expression Evaluation Order for Idiomatic C++, this was part of the Pre-Urbana mailing that came out this October The introduction says (emphasis mine going forward):
Expression evaluation order is a recurring discussion topic in the C++ community. In a nutshell, given an expression such as f(a, b, c), the order in which the sub-expressions f , a , b , c are evaluated is left unspecified by the standard. If any two of these sub-expressions happen to modify the same object without intervening sequence points, the behavior of the program is undefined. For instance, the expression f(i++, i) where i is an integer variable leads to undefined behavior
it proposes:
We propose to revise C++ evaluation rules to support decades-old idiomatic constructs and programming practices. A simple solution would be to require that every expression has a well-defined evaluation order. That suggestion has traditionally met resistance for various reasons. Rather, this proposes suggests a more targeted fix
- Postfix expressions are evaluated from left to right. This includes functions calls and member section expressions.
- Assignment expressions are evaluated from right to left. This includes compound assignments.
- Operands to shift operators are evaluated from left to right
Update
Herb Sutter recently put out a poll on order of evaluation looking for some feedback from the community on what result we would expect from the following code:
std::vector<int> v = { 0, 0 };
int i = 0;
v[i++] = i++;
std::cout << v[0] << v[1] << endl;
This would seem to indicate the committee is looking at the topic of order of evaluation seriously but as we can see from the discussion this is controversial.
回答2:
No it is still unspecified in C++11. This is so your compilers can do micro optimizations that would improve the quality of the code, and is varied from compiler to compiler. Try printf with increment operations on different compilers.
functions like int i = foo(3) + bar(0); has undefined behaviors, no function is guaranteed to operate first.
来源:https://stackoverflow.com/questions/26911377/parameter-order-evaluation