Nemanja I.
Nemanja I.

Reputation: 19

Strange cout output (code blocks codeblocks-16.01mingw-setup.exe)

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;
}

Upvotes: 1

Views: 140

Answers (2)

Richard Hodges
Richard Hodges

Reputation: 69902

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?

Upvotes: 1

Naomi
Naomi

Reputation: 5486

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)

Upvotes: 2

Related Questions