表达式的评价顺序 [英] Order of evaluation of expression

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

问题描述

我刚读过,运算符的求值顺序和优先级是不同的,但在C ++中是相关的概念。但我仍然不清楚这些是如何不同但相关的。

  int x = c + a * b; // 31 
int y =(c + a)* b; // 36

上述语句对评估顺序有什么影响。例如当我说(c + a)通过改变表达式的优先级改变表达式的顺序?

解决方案

评估顺序的重要部分是任何组件是否有副作用。



p>

  int i = c()+ a()* b 

其中 a b 有副作用:

  int global = 1; 

int a(){
return global ++;
}
int b(){
return ++ global;
}
int c(){
return global * 2;
}

编译器可以选择调用 a ) b() c(),然后将结果插入表达式。此时,优先级将接管并决定应用 + * 运算符的顺序。



在此示例中,最可能的结果是


  1. 编译器将评估 c(),然后按 a(),然后导致 i = 2 + 1 * 3 = 5

  2. 编译器将评估 b code>,然后是 a(),然后是 c(),结果是 i = 6 + 2 * 2 = 10

但是编译器可以自由选择

告诉你操作符应用于参数的顺序( * 之前),而评估顺序会告诉您参数是以什么顺序解析的( a() b() c())。这就是为什么他们不同但相关。


I've just read that order of evaluation and precedence of operators are different but related concepts in C++. But I'm still unclear how those are different but related?.

int x = c + a * b;    // 31
int y = (c + a) * b;  // 36

what does the above statements has to with order of evaluation. e.g when i say (c + a) am i changing the order of evaluation of expression by changing its precedence?

解决方案

The important part about order of evaluation is whether any of the components have side effects.

Suppose you have this:

int i = c() + a() * b();

Where a and b have side effects:

int global = 1;

int a() {
    return global++;
}
int b() {
    return ++global;
}
int c() {
    return global * 2;
}

The compiler can choose what order to call a(), b() and c() and then insert the results into the expression. At that point, precedence takes over and decides what order to apply the + and * operators.

In this example the most likely outcomes are either

  1. The compiler will evaluate c() first, followed by a() and then b(), resulting in i = 2 + 1 * 3 = 5
  2. The compiler will evaluate b() first, followed by a() and then c(), resulting in i = 6 + 2 * 2 = 10

But the compiler is free to choose whatever order it wants.

The short story is that precedence tells you the order in which operators are applied to arguments (* before +), whereas order of evaluation tells you in what order the arguments are resolved (a(), b(), c()). This is why they are "different but related".

这篇关于表达式的评价顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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