简体   繁体   English

C ++表达式评估。 “评估”是什么意思?

[英]C++ Expression evaluation. What does 'evaluation' mean?

I understand the problems with the classic example of 我理解经典例子的问题

int i=0;
foo(i++, i++);

but I can't convince myself of whether the following is valid or invalid 但我不能说服自己以下是有效还是无效

int foo(int& i)
{
   i=42;
   return 99;
}

bar(foo(i), i);

I understand that the order 'foo(i)' and 'i' are evaluated is undefined, but what exactly does 'evaluated' mean? 据我所知,'foo(i)'和'i'的评估顺序是未定义的,但'评估'究竟是什么意思? ie will the 2nd parameter of bar always be 42, or can the current value of 'i' be passed in before foo changes it? 也就是说bar的第二个参数总是42,或者在foo改变它之前是否可以传入'i'的当前值?

No it is not guaranteed. 不,不保证。
The order of evaluation of arguments to an function is Unspecified [Ref 1] . 函数参数的评估顺序是Unspecified [Ref 1]
It can be possible that either: 它可能是:

  • foo(i) gets evaluated first or foo(i)首先得到评估或
  • i gets evaluated or i得到评估或
  • any other magical order( in case number of arguments were more than two ) 任何其他神奇的顺序( 如果参数的数量超过两个

Unspecified in this context means the implementation is allowed to implement the said feature whichever way they want and it need not be documented. 在此上下文中未指定意味着允许实现以他们想要的方式实现所述特征,并且不需要记录。


[Ref 1] [参考1]
C++03 5.2.2 Function call Para 8 C ++ 03 5.2.2函数调用第8段

The order of evaluation of arguments is unspecified . 参数的评估顺序未指定 All side effects of argument expression evaluations take effect before the function is entered. 参数表达式求值的所有副作用在输入函数之前生效。 The order of evaluation of the postfix expression and the argument expression list is unspecified. 未指定后缀表达式和参数表达式列表的评估顺序。

This sample (gcc 4.6) 这个样本(gcc 4.6)

#include <iostream>
using namespace std;

int foo(int& i)
{
    i=42;
    return 99;
}

void bar(int i, int j)
{
    cout << "i = " << i << "; j = " << j << endl;
}

int main()
{
    int i =10;
    bar(foo(i), i);
    return 0;
}

gives i = 99, j = 10. 给出i = 99,j = 10。

So it is really not guaranteed. 所以它真的不能保证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM