precendence VS用C短路 [英] Precendence vs short-circuiting in C

查看:675
本文介绍了precendence VS用C短路的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int i=-3, j=2, k=0, m; 
m = ++i || ++j && ++k; 
printf("%d, %d, %d, %d\n", i, j, k, m);

由于 ++ 有更多的precedence比 || &安培; &安培; 在C,它们首先评估,因此前pression变得 M = -2 || 3和;&放大器; 1 。现在,您可以申请短路而产生不正确的答案。这是为什么?

Since ++ has more precedence than || and && in C, they are evaluated first and therefore the expression becomes m = -2 || 3 && 1. Now you can apply short circuiting but that produces incorrect answer. Why is that?

推荐答案

<一个href=\"http://blogs.msdn.com/b/ericlippert/archive/2008/05/23/$p$pcedence-vs-associativity-vs-order.aspx\"相对=nofollow> precedence&NE;为了评价。

|| 的短路行为和&放大器;&安培; 意味着他们的左侧边首先计算,以及

The short-circuiting behavior of || and && means that their left-hand sides are evaluated first, and


  • 如果的LHS || 为真(非零),等式右边不计算(因为前pression将真正无论RHS是什么)

  • 如果的LHS &放大器;&安培; 计算结果为假(或零),RHS不计算(因为前pression将无论RHS是什么)

  • If the LHS of || evaluates to true (nonzero), the RHS is not evaluated (because the expression will be true no matter what the RHS is)
  • If the LHS of && evaluates to false (or zero), the RHS is not evaluated (because the expression will be false no matter what the RHS is)

在你的榜样, ++我被评估,等于-2,这是为零,因此 || (即 ++ J&安培;&安培; ++氏/ code>)永远不会被计算:Ĵ K 从不递增。

In your example, ++i gets evaluated, and is equal to -2, which is nonzero, so the right-hand side of the || (that is, ++j && ++k) never gets evaluated: j and k are never incremented.

这篇关于precendence VS用C短路的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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