Function called in cout

I ran this program in two different systems using Mingw compiler and Sublime Text 3 for writing code, but I got two different results:
In first system:
89842414i love 5

In second system:
898i love 424145

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
using namespace std;

int myfunction(int p)

{
  p++;
  cout<<p;

  return 5;
}


int main()
{
  int x;
  x=7;
  x++;
  cout<<x;
  myfunction(x);
  cout<<x;

  cout<<"i love "<<myfunction(42413);


 return 0;
}
Last edited on
Lets try with more verbosity:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using std::cout;

int myfunction(int p)
{
  p++;
  cout << "F " << p << '\n';
  return 5;
}

int main()
{
  int x=7;
  x++;
  cout << "Ma " << x << '\n';
  myfunction(x);
  cout << "Mb " << x << '\n';
  cout << "i love " << myfunction(42413);
}

Ma 8
F 9
Mb 8
F 42414
i love 5 

This all boils down to expression cout << "i love " << myfunction(42413)
Lets write that as cout << A << B
Operator evaluation order says that it is equivalent to (cout << A) << B
That is, that cout << A evaluates before cout << B.
Good so far.

The B is an expression, whose value has to be evaluated before we can do cout << B.

However, there is no rule saying when. Only rule is that it must be within the statement and done before << B

One system does it:
1. evaluate B
2. cout << A
3. cout << value_of(B)

The other:
1. cout << A
2. evaluate B
3. cout << value_of(B)

Both are valid. Your function has a side effect with unpredictable manifestation.
But why? The compiler is same, OS is same. So what is the difference between the systems. Any reason?
For all we know, the compiler could base its decision on the state of the moons of Jupiter.
The compiler is same

Such things can change between different versions of the same compiler.
Topic archived. No new replies allowed.