简体   繁体   中英

c++ function call within cout statement

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.

std::cout << f() << g();

The order of evaluation of the two function calls is unspecified; the compiler can call g() then f() , or it can call f() then g() .

Same thing in your code; the compiler can squirrel away the value of aa[0] the call ab() , or it can call ab() then grab the value of aa[0] .

Function evaluation in an expression depends on compiler stream operations such as << and >> . The same problem that happens when you evaluate x = f1() + f2() . You don't know which will be evaluated first because it's compiler dependent.

It would be more safe to call these on separate lines to rule out the ambiguity.

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