使用std :: cout时顺序相反 [英] Reverse order when using std::cout

查看:112
本文介绍了使用std :: cout时顺序相反的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的程序输出10。我希望它先打印0(功能f的else分支),然后打印1。为什么顺序相反?

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

输出

10


推荐答案

未指定函数参数的评估顺序。因此,您在左侧有此参数:

The order of evaluation of arguments to a function is unspecified. So, you have this argument on the left:

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

右边的这个:

f(b)

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

Both being passed to operator<< (the last one). Either one can be evaluated first. If the one on the left is evaluated first, then the call to f(b) on the left will happen first, and return 0. Then the one on the right will be called and return 1, resulting in an output of 01. If the one on the right is evaluated first, then it will return 0, and the one on the left will then be called, returning 1, resulting in the reversed output of 10.

这篇关于使用std :: cout时顺序相反的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆