简体   繁体   English

运算符优先级在C ++中的行为不正常

[英]Operator precedence doesn't behave as expected in c++

Consider this code : 考虑以下代码:

int func1()
{
    cout<<"Plus"<<endl;
    return 1;
}
int func2()
{
   cout<<"Multiplication"<<endl;
   return 2;
}
int main()
{
  cout<<func1()+4*func2();
}

According to this page * operator has higher precedence than + operator So I expect the result to be : 根据此页面, *运算符的优先级高于+运算符,因此我希望结果是:

Multiplication 
Plus
9

But the result is 但是结果是

Plus 
Multipication
9

!! !! What is going on in compiler parser ?! 编译器解析器中发生了什么? Does compiler prefer Operator associaty ? 编译器是否喜欢运算符关联? Is the output same in all c/c++ compilers? 所有c / c ++编译器的输出是否相同?

Operator precedence is not the same thing as order of evaluation. 运算符优先级与求值顺序不同。

You have no guarantee about the order of evaluation - the compiler is free to call functions in whatever order it likes within an expression so long as you get the correct result. 您无法保证求值的顺序-编译器可以随意在表达式中以任意顺序调用函数,只要您获得正确的结果即可。

(A minor qualification: anything which introduces a sequence point (which includes short circuit operators), will have an effect on order of evaluation, but there are no sequence points within the expression in this particular case.) (一个次要条件:任何引入序列点的东西(包括短路算子)都会影响求值顺序,但是在这种情况下表达式中没有序列点。)

The compiler is free to evaluate functions in any order it pleases - the only cases within expressions where the order of evaluation is guaranteed are the sequence points; 编译器可以随意按任意顺序评估函数-表达式中唯一保证评估顺序的情况是顺序点; operators || 运营商|| , && , , , and ? &&,? of the ternary conditional operator ? : 三元条件运算符? : ? : are sequence points. ? :是序列点。 In each case the left side has all its values and side effects evaluated before the right side is touched. 在每种情况下,触摸左侧之前都要评估左侧的所有值和副作用。

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

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