gpt4 book ai didi

c - 后增量运算符与 and & or 运算符的工作差异

转载 作者:太空宇宙 更新时间:2023-11-04 08:10:27 25 4
gpt4 key购买 nike

这种后增量运算符的用法令人困惑。

{int a=0,b=1,c=2,d;
d=a++||b++||c++
printf("%d %d %d %d",a,b,c,d);}

输出是

1,2,2,1

c 的值没有增加,但如果我用 && 运算符替换它,它会增加。为什么?

最佳答案

引用 C11,第 6.5.14 章,(强调我的)

Unlike the bitwise | operator, the || 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 unequal to 0, the second operand is not evaluated.

所以,在你的情况下,

 d=a++||b++||c++

相同
 d= ( (a++ || b++) || c++)      

然后,计算第一个括号内的语句,首先 a++(后增量)计算为 0(副作用未决),因此第一个 || 被评估,b++,产生 1,|| 操作的结果为 TRUE,产生 1。

结果 1 是第二个 || 的 LHS。因此,第二个 || (c++) 的 RHS 不再计算,最终结果变为 TRUE,再次产生 1,这得到存储在 d 中。

最后,

  • a++ 被求值,变成 1
  • b++ 被求值,变成 2
  • c++ 求值,仍然是 2
  • ||的结果存入d,为TRUE,所以存1。

另一方面,对于逻辑 AND && 运算符,

[...] If the first operand compares equal to 0, the second operand is not evaluated.

因此,如果将最后一个 || 替换为 &&,那么对于外部语句,LHS 变为 1,RHS 求值,使得 c++ 作为副作用进行计算和递增。

关于c - 后增量运算符与 and & or 运算符的工作差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39942605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com