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?