使用 std::cout 评估参数的顺序 [英] Order of evaluation of arguments using std::cout

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

问题描述

大家好,我今天偶然发现了这段代码,我对究竟发生了什么以及更具体的顺序感到困惑:

Hi all I stumbled upon this piece of code today and I am confused as to what exactly happens and more particular in what order :

代码:

#include <iostream>

bool foo(double & m)
{
    m = 1.0;
    return true;
}

int main()
{
    double test = 0.0;
    std::cout << "Value of test is : 	" << test << "	Return value of function is : " << foo(test) <<  "	Value of test : " << test << std::endl;
    return 0;
}

输出为:

Value of test is :      1       Return value of function is : 1 Value of test : 0

看到这一点,我会假设在调用函数之前以某种方式打印了最正确的参数.所以这是从右到左的评价??在调试过程中,尽管似乎在输出之前调用了该函数,这正是我所期望的.我使用的是 Win7 和 MSVS 2010.感谢您的帮助!

Seeing this I would assume that somehow the right most argument is printed before the call to the function. So this is right to left evaluation?? During debugging though it seems that the function is called prior to the output which is what I would expect. I am using Win7 and MSVS 2010. Any help is appreciated!

推荐答案

未指定表达式中元素的求值顺序(某些非常特殊的情况除外,例如 &&|| 运算符和三元运算符,它们引入了序列点);所以,不能保证 test 会在 foo(test) (修改它)之前或之后被评估.

The evaluation order of elements in an expression is unspecified (except some very particular cases, such as the && and || operators and the ternary operator, which introduce sequence points); so, it's not guaranteed that test will be evaluated before or after foo(test) (which modifies it).

如果您的代码依赖于特定的求值顺序,获得它的最简单方法是将您的表达式拆分为多个单独的语句.

If your code relies on a particular order of evaluation the simplest method to obtain it is to split your expression in several separated statements.

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

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