0

I was trying to understand the following two codes. I used Visual Studio 2017 to compile and run the programs but I cannot understand how the code is executed.

#include <iostream>
using namespace std;
class A
{
public:
  A()
  {
    a[0] = 1;
    a[1] = 0;
  }
  int a[2];
  int b(void)
  {
    int x = a[0];
    a[0] = a[1];
    a[1] = x;
    return x;
  }
};

int main() {
  A a;
  a.b();
  cout << a.b() << a.a[1] << endl;
  return 0;
}

My expected result is 00. But when I run the program in Visual Studio 2017, the answer is 01.

Also, when I separate cout for two lines as follows, the answer is 00.

#include <iostream>
using namespace std;
class A
{
public:
  A()
  {
    a[0] = 1;
    a[1] = 0;
  }
  int a[2];
  int b(void)
  {
    int x = a[0];
    a[0] = a[1];
    a[1] = x;
    return x;
  }
};

int main() {
  A a;
  a.b();
  cout << a.b();
  cout << a.a[1] << endl;
  return 0;
}

I tried several online compilers, and both of the above codes give 00 as the answer. Can someone please explain what is the reason for this?

sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • Did you try stepping through the code with a debugger? – Quimby Jul 14 '22 at 17:14
  • 3
    In the statement `cout << a.b() << a.a[1] << endl;` there's no way to tell which sub-expression will be evaluated first: `a.b()`, `a.a[1]`, or even `endl`. The output order is defined, the evaluation order isn't. – Some programmer dude Jul 14 '22 at 17:15
  • Yes. I debugged both these codes. Values of the array of `a` is modified during the program execution. But that is not printed correctly in the first program. – Lahiru Dilshan Jul 14 '22 at 17:16
  • 1
    Your first program does not ensure that `a.b()` is evaluated _before_ `a.a[1]`. Your second program does. – Drew Dormann Jul 14 '22 at 17:20
  • I got the answer to the question. [link](https://stackoverflow.com/questions/7718508/order-of-evaluation-of-arguments-using-stdcout) – Lahiru Dilshan Jul 14 '22 at 17:22

0 Answers0