1

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>
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;
    }
}
Community
  • 1
  • 1
user963241
  • 6,015
  • 16
  • 59
  • 86

2 Answers2

4
 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!

Nawaz
  • 327,095
  • 105
  • 629
  • 812
0

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! :-)

Bo Persson
  • 86,087
  • 31
  • 138
  • 198