2

Consider the following code. expected output should be
0 1
1 2
2 3
and so on.

#include<iostream>
using namespace std;

int f=0;

int B()
{
  return f; 
}

int A()
{
  return f++;
}

int main()
{
  cout<<A()<<" "<<B()<<endl;
  cout<<A()<<" "<<B()<<endl;
  cout<<A()<<" "<<B()<<endl;
  cout<<A()<<" "<<B()<<endl;
  return 0;
}

but the actual output is
0 0
1 1
2 2
and so on.. why?

and if i change code like this-

int main()
{
  int f=0;
  cout<<f++<<" "<<f<<endl;
  cout<<f++<<" "<<f<<endl;
  cout<<f++<<" "<<f<<endl;
  cout<<f++<<" "<<f<<endl;
  return 0;
}

then i get correct expected output
why?

  • All those `<<` just hide a bunch of normal function calls. The order in which arguments to function calls are evaluated is undefined. Therefore, there is no order defined by The Standard for `A()` and `B()` to be called. (And the same is true for `f++` and `f`, it just happens to come out differently). – BoBTFish Feb 04 '17 at 09:33

1 Answers1

0

The order of evaluation of the operands of << is not specified. So

cout << A() << " " << B() << endl;

can be treated as either:

temp1 = A();
temp2 = B();
cout << temp1 << " " << temp2 << endl;

or as:

temp2 = B();
temp1 = A();
cout << temp1 << " " << temp2 << endl;

Performing side effects on a variable and accessing it without defined sequencing results in undefined behavior.

Barmar
  • 741,623
  • 53
  • 500
  • 612