【问题标题】:Precedence of || and && operators in C [duplicate]|| 的优先级C中的和&&运算符[重复]
【发布时间】:2015-08-07 18:37:53
【问题描述】:
#include <stdio.h>
int main()
{
   int i=-3,j=2,k=0,m;
   m = ++i || ++j && ++k;
   printf("%d %d %d %d", i, j, k, m);
}

输出:

-2 2 0 1

为什么要表达m=++i||++j&amp;&amp;++k;不解析为m=++i||(++j&amp;&amp;++k),因为&&的优先级高于|| ??

【问题讨论】:

  • 非常巧合的是,您的程序使用与重复问题完全相同的变量和值。 :)
  • @Barmar 它没有;副本根本不使用||
  • 啊,除了第一个 &amp;&amp; 已更改为 || 之外,它们是相同的。
  • 运算符优先级 != 求值顺序 && 从左到右的关联性 != 从左到右求值。

标签: c


【解决方案1】:

||&amp;&amp; 是短路运算符。如果从左操作数计算最终结果,则计算右操作数。

++i ||  /* Evaluate ++i which is -2, so the result of expression is 1 */
  ++j && ++k;  /* No need to evaluated this */

【讨论】:

  • 这不能保证并且特定于编译器实现。
  • 不,这是由规格保证的
  • @Atmocreations 类 C 语言中的逻辑运算符总是被标准短路
  • @Atmocreations 6.5.13/4 "...the &amp;&amp; operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares equal to 0, the second operand is not evaluated." 标准再清楚不过了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-09
  • 1970-01-01
  • 2014-11-09
  • 2021-03-16
  • 2015-01-04
  • 2015-04-17
  • 2021-03-29
相关资源
最近更新 更多