1

When I run this program I get strange output 1132. Can somebody explan me why is 1132?

//main.cpp
#include <iostream>
using namespace std;

int f1(int &a){return a++;}
int f2(int &a){return ++a;}

int main(){
    int x, y;
    int *px, *py;
    x = 1;
    y = 2;
    px = &x;
    py = &y;
    cout << f1(*px) << *px << f2(*py) << *py << "\n";

    return 0;
}
Nemanja I.
  • 19
  • 1

2 Answers2

2

The order of evaluation in your case was right-to-left.

Note that there is no guarantee for a left-to-right evaluation.

So order was:

  1. *py

  2. f2(*py)

  3. *px

  4. f1(*px)

Only then the << operators ran (and were evaluated left-to-right as expected)

Shloim
  • 4,881
  • 19
  • 34
1

In this line:

cout << f1(*px) << *px << f2(*py) << *py << "\n";

The compiler is free to evaluate each expression in any order (even though the order of execution of operator<< is left to right).

The expressions are:

f1(*px)
f2(*py)
*px
*py

The evaluation order may be any one of the npr(4,4) permutations.

npr(4,4) = 4! / (4-4)! = 24

Do you feel lucky?

Richard Hodges
  • 66,334
  • 6
  • 85
  • 131