1
using namespace std;

int foo1(int &n);
int foo2(int n);

int main() {
    int n1, n2;
    cout << foo1(n1) << n1 << foo2(n2) << endl;
}

int foo1(int &n) {
    n = 3;
    return 1;
}

int foo2(int n) {
    return 2;
}

and I get output 1 (trash val) 2.

Why n1's value is not modified? foo1() is worked faster than cout << n1;? When reference var's value modified?

costaparas
  • 5,047
  • 11
  • 16
  • 26
omegafrog
  • 15
  • 3
  • 1
    Please state which language standard you are working to: `c++17` or... ? – G.M. Dec 24 '20 at 10:51
  • I suppose that you are using MSVC of c++14 or older, since I've spotted the same problem once, and it turned out that the order of calculation in a single sentence cannot be guaranteed before c++17. – SHP Dec 24 '20 at 10:51
  • 2
    Does this answer your question? [Order of evaluation of arguments using std::cout](https://stackoverflow.com/questions/7718508/order-of-evaluation-of-arguments-using-stdcout) And take a look at the [second answer there](https://stackoverflow.com/a/50361541/5105949). Pre C++17 the behaiour is unspecified. – Lukas-T Dec 24 '20 at 11:20
  • thank you. I'm using c++11 and I understand! :) – omegafrog Dec 24 '20 at 13:51

1 Answers1

1

This

cout << foo1(n1)<<n1<<foo2(n2)<<2ndl;

actually resolves to

operator<<(operator<<(operator<<(operator<<(cout, foo(n1)), n1), foo2(n2)), endl);

The order of arguments evaluation is not defined by the standard. It's an implementation dependent. So here

operator<<(operator<<(cout, foo(n1)), n1)

either can be evaluated first. And in your case it appears n1 took the first place and then operator<<(cout, foo(n1))

4xy
  • 3,494
  • 2
  • 20
  • 35