简体   繁体   中英

structure and functions in C++

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;
}

In the cout line, ab() could either be called before or after aab 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.

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 ab() or aab 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM