开发者

Order vs. Associativity [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

cout << order of call to functions it prints?

What is the difference between order and associativity when evaluating a compound expression?

In the following example, I don't see the effect of order on the result of expression. The result is always 3 like the functions would have been called from left to right as arithmetic operators being left associative.

#include <iostream&开发者_运维百科gt;
using std::cout;
using std::endl;

int Func1(int &i)
{
    return i;
}

int Func2(int &i)
{
    return i++;
}

int main()
{
    for (int index = 0; index < 999999999; index++)
    {
        int i = 0;

        int result = (Func2(i) + Func1(i) + Func1(i) + Func2(i));

        cout << result << endl;
    }
}


 int result = (Func2(i) + Func1(i) + Func1(i) + Func2(i));

The order in which these functions are called is unspecified by the language!

The section $5/4 from the C++ Standard (2003) reads,

Except where noted, 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 the free advice is : avoid writing such code. They're non-portable!


The result is very likely to be the same if you run the code multiple times, using the same compiler with the same compile options. However, if you change the options or try another compiler, you can get a different result.

As you use only simple functions on ints, there is nothing much to be gained from calling the functions in a different order, so either left-to-right or right-to-left would be the obvious choice. And your test code can't tell the difference! :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜