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

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

问题描述



代码:



  #include< iostream> 

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

int main()
{
double test = 0.0;
std :: cout<< 测试的价值是:\t<测试< \tReturn value of function is:<< foo(test)<< \tValue of test:<<测试< std :: endl;
return 0;
}

输出为:

 测试值为:1函数的返回值为:1测试值:0 

看到这里,我会假设在调用函数之前打印最右边的参数。所以这是右边的评价??在调试期间,似乎该函数在输出之前调用,这是我所期望的。我使用Win7和MSVS 2010.任何帮助是赞赏的。

解决方案

表达式中元素的评估顺序未指定一些非常特殊的情况,例如&& || 运算符和三元运算符,如果您的代码依赖于特定的求值顺序,那么获取它的最简单的方法是将表达式拆分成几个单独的语句。


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 :

Code :

#include <iostream>

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

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

The output is :

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

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!

解决方案

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).

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天全站免登陆