0

The program below outputs 10. I expected it to first print 0 (the else branch of function f) and then to print 1. How come that the order is reversed?

#include <iostream>     
using namespace std;

int f(bool& b){
    if (b==true){
        return 1;
    } else {
        b=true;
        return 0;
    }
}

int main () {
    bool b=false;
    cout<<unitbuf<<f(b)<<unitbuf<<f(b);

  return 0;
}

The output

10
4

1 回答 1

5

未指定函数参数的评估顺序。所以,你在左边有这个论点:

(cout << unitbuf << f(b) << unitbuf)

而右边这个:

f(b)

两者都被传递给operator<<(最后一个)。任何一个都可以先评估。如果左边的第一个被评估,那么f(b)左边的调用将首先发生,并返回 0。然后右边的将被调用并返回 1,导致输出为01。如果首先计算右边的那个,那么它将返回 0,然后调用左边的那个,返回 1,从而产生 的反向输出10

于 2013-08-07T02:48:03.253 回答