简体   繁体   English

和&或运算符在后增量运算符上的工作差异

[英]diffrence in working of post increment operator with and & or operator

This post-increment operator usage is confusing. 这种后递增运算符的用法令人困惑。

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

output is 输出是

1,2,2,1 1,2,2,1

value of c did not increase but if I replace it with && operator it increases. c值没有增加,但是如果我用&&运算符替换它,它的值会增加。 Why? 为什么?

Quoting C11 , chapter §6.5.14, ( emphasis mine ) 引用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. 如果第一个操作数比较不等于0 ,则不计算第二个操作数。

So, in your case, 所以,就您而言,

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

is the same as 是相同的

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

Then, the statement inside the first parenthesis is evaluated, first a++ (post-increment) evaluates to 0 (side-effect pending), so the RHS of the first || 然后,评估第a++括号内的语句,首先将a++ (后递增)评估为0(待处理的副作用),因此第一个||的RHS。 is evaluated, b++ , producing 1 and the result of the || 被求值b++ ,产生1和||的结果 operation is TRUE, yields 1. 运算为TRUE,得出1。

That result, 1 , is the LHS of the second || 结果1是第二个||的LHS。 . Hence, the RHS of the second || 因此,第二个||的RHS ( c++ ) is not evaluated anymore and the final result becomes TRUE, again yielding 1 , which gets stored in d . c++ )不再进行求值,最终结果变为TRUE,再次产生1 ,并将其存储在d

So, finally, 所以,最后,

  • a++ is evaluated, becomes 1 a++被评估为1
  • b++ is evaluated, becomes 2 b++评估为2
  • c++ is not evaluated, remains 2 c++ 评估,仍为2
  • the result of || ||的结果 is stored in d , that is TRUE, so stores 1. 存储在d ,即为TRUE,因此存储1。

On the other hand, for logical AND && operator, 另一方面,对于逻辑AND &&运算符,

[...] If the first operand compares equal to 0, the second operand is not evaluated. [...]如果第一个操作数比较等于0,则不评估第二个操作数。

So, if you replace the last || 因此,如果您替换最后一个|| with && , then for the outer statement, the LHS becomes 1 and the RHS evaluates, making c++ to be evaluated and incremented, as a side effect. 使用&& ,然后对于外部语句,LHS变为1,并且RHS进行评估,使c++被评估并增加,这是一个副作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM