如果++(pre /后)有较高的precedence,为什么和放大器;&安培;正在首先计算? [英] If ++ (pre/post) have higher precedence, why && is being evaluated first?

查看:118
本文介绍了如果++(pre /后)有较高的precedence,为什么和放大器;&安培;正在首先计算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的程序:

 int main(void)
 {
  int i, j, k, m;
  i=-3, j=2, k=0;
  m = k++ && ++i && ++j;
  printf("%d, %d, %d, %d\n", i, j, k, m);
 return 0;
 }

上面的程序的输出是:

The output of the program above is:

 -3 2 1 0 

但是,根据运营商precedence表,++应该先进行评估,我猜。
我也试图把括号他们身边,但还是输出保持不变。
我读的地方,把括号围绕将使评估第一,不管是什么。

But according to operator precedence table, ++ should have evaluated first I guess. I also tried putting parenthesis around them, but still the output remains same. I read somewhere that putting parenthesis around will make it evaluate first, no matter what.

一个人,请说清楚,它是如何计算。
先谢谢了。

Somebody, please make it clear, how it's evaluated. Thanks in advance.

推荐答案

您混淆的 precedence 为了评估的。 precedence定义的操作数的分组方式。 ++ 的高precedence使得前pression等同于:

You are confusing precedence with order of evaluation. Precedence defined how the operands are grouped. The higher precedence of ++ makes the expression equivalent to:

m = (k++) && (++i) && (++j);

但评估顺序是无关紧要的。 &安培; 担保​​和放大器的快捷电路
其左侧操作数先计算。

But the evaluation order is irrelevant. The shortcut circuit of && guarantees that its left-hand operand is evaluated first.

在一般情况下,大多数运营商没有明确规定评价的顺序,有四个例外:逻辑与&放大器;&安培; ,逻辑或 | ?| ,条件运算符和逗号操作符

In general, most operator doesn't specify the order of evaluation, with four exceptions: logical AND &&, logical OR||, conditional operator ?: and comma operator ,.

作为不同的顺序评价的一个具体的例子:

As a concrete example of different order of evaluation:

由于 INT I = 0 的结果我+(我++)是不确定的,编译器评估板我++ 第一,它修改的值 I ,编译器可以选择的计算结果 I 第一。你应该避免前pressions这样的。

Given int i = 0, the result of i + (i++) is unspecified, the compiler may evaluates i++ first, which modifies the value of i, the compiler may choose to evaluates i first. You should avoid expressions like these.

在另一方面,结果 I和;&安培; (我++)确定,如&放大器;&安培; 确保了左操作数 I 是首先计算,因为它是零,右边的操作数我++ 不会求。

On the other hand, the result of i && (i++) is determined, as && ensures the left operand i is evaluated first, since it's zero, the right operand i++ is never evaluated.

这篇关于如果++(pre /后)有较高的precedence,为什么和放大器;&安培;正在首先计算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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