I'm learning c++, and recently run into a confusing problem, here's the code:
#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(void) {
A a;
cout<<a.a[0]<<a.a[1]<<endl; //outputs 10
a.b();
cout<<a.a[0]<<a.a[1]<<endl; //outputs 01
a.b();
cout<<a.a[0]<<a.a[1]<<endl; //outputs 10
cout << a.b() << //outputs 1
endl<< a.a[0]<<a.a[1] << endl; //outputs 10???
cout<<a.a[0]<<a.a[1]<<endl; //outputs 01???
return 0;
}
The first two calls of b() behaves as expected, but when i call b() within the cout statement, it doesn't switch the two elements of the array right away, but later i check it, it's already switched.
Can you help me understand this behavior? Thank you.