Reputation: 1
Can someone explain why this code gives the output 10? When I try to analyse it my logic gives as result 11.
#include <iostream>
using namespace std;
class A {
public:
A() { a.a = a.b = 1; }
struct { int a,b; } a;
int b(void);
};
int A::b(void) {
int x=a.a;
a.a=a.b;
a.b=x;
return x;
};
int main(void) {
A a;
a.a.a = 0;
a.b();
cout << a.b() << a.a.b << endl;
return 0;
}
Upvotes: 0
Views: 83
Reputation: 51
Other than using a debugger, you can also use cout
statements to help keep track of when things are called.
To kind of help myself out tracing your program I fixed a bit of the indentation and added comments as to when things are happening:
#include <iostream>
using namespace std;
class A {
public:
A() {
a.a = a.b = 1;
}
struct {
int a,b;
} a;
int b(void);
};
int A::b(void) {
cout << "Within A::b()" << endl;
// swap a.a, a.b
int x=a.a;
a.a=a.b;
a.b=x;
cout << "a.a.a = " << a.a << " a.a.b: " << a.b << endl;
return x;
};
int main(void) {
// sets a.a.a = 1, a.a.b = 1
A a;
// sets a.a.a = 0, a.a.b = 1
a.a.a = 0;
// a.a.a = 1, a.a.b = 0
a.b();
// check output here
cout << a.b() << a.a.b << endl;
return 0;
}
The above program results with the following output on http://cpp.sh/ :
Within A::b()
a.a.a = 1 a.a.b: 0
Within A::b()
a.a.a = 0 a.a.b: 1
10
In all, it depends on whether or not a.b() or a.a.b is resolved first when you call cout
. In this case, operator precedence is undefined due to how cout
works. This stackoverflow post has some good info on this.
Upvotes: 0
Reputation: 141554
In the cout
line, a.b()
could either be called before or after a.a.b
is evaluated. Beginners sometimes assume left-to-right evaluation in this sort of code but actually that is not a rule of C++.
Those two different possibilities would explain your 10
and 11
. To avoid ambiguity you could write:
cout << a.b();
cout << a.a.b << endl;
(assuming that order was your intent).
Note: C++17 may change this and define left-right evaluation order for this code.
Upvotes: 2