问题运营商precedence [英] Problem with operator precedence

查看:169
本文介绍了问题运营商precedence的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在O / P出来是X = 2,Y = 1,Z = 1的犯规与运营商precedence同意。我于涡轮C ++编译器运行以下命令:

 无效的主要()
{
    INT的x,y,Z,Q;
    X = Y = Z = 1;
    Q = ++点¯x|| ++ Y'放大器;&安培; ++ Z者除外;
    的printf(x =%d个Y =%d个Z =%d个,X,Y,Z);
}


解决方案

操作precedence不以任何方式确定该运营商的执行顺序。操作precedence只定义了运营商和他们的操作数之间的分组。在你的情况下,运营商precedence说,前pression

  Q = ++点¯x|| ++ Y'放大器;&安培; ++ž

被归纳为

  Q =((++ x)||((++ Y)和放大器;及(++ Z)))

各地拥有绝对无关,与运营商precedence可言。

其余的是由每一个具体的操作者的语义确定。在这种情况下的顶级运营商为 || || 运营商的具体特性是,它总是先评估其左侧。如果左侧大小原来是非零,那么它甚至不尝试评估右手侧

这是你的情况究竟会发生什么。左侧面是 ++ X ,它的计算结果为非零值。这意味着它们的整个前$ P $给定的初始值pssion是功能上等同于一个单纯的

  Q =(++到X!= 0)

|| 运营商甚至没有触及。右手边

The O/p comes out to be x=2,y=1,z=1 which doesnt agree with the operator precedence. I was running this on Turbo c++ compiler:

void main()
{
    int x,y,z,q;
    x=y=z=1;
    q=++x || ++y && ++z;
    printf("x=%d y=%d z=%d",x,y,z);
}

解决方案

Operator precedence does not in any way determine the order in which the operators are executed. Operator precedence only defines the grouping between operators and their operands. In your case, operator precedence says that the expression

q = ++x || ++y && ++z

is grouped as

q = ((++x) || ((++y) && (++z)))

The rest has absolutely nothing to do with operator precedence at all.

The rest is determined by the semantics of each specific operator. The top-level operator in this case is ||. The specific property of || operator is that it always evaluates its left-hand side first. And if the left-hand size turns out to be non-zero, then it does not even attempt to evaluate the right-hand side.

This is exactly what happens in your case. The left-hand side is ++x and it evaluates to a non-zero value. This means that your whole expression with the given initial values is functionally equivalent to a mere

q = (++x != 0)

The right-hand side of || operator is not even touched.

这篇关于问题运营商precedence的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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