简体   繁体   English

为什么变量不增加?

[英]Why isn't the variable being incremented?

Increment operator not working. 增量运算符不起作用。

I was learning C language expressions. 我正在学习C语言表达。 I've also tried different combinations of increment operators (prefix and postfix) on the variables but the output is coming out to be same. 我还尝试了对变量使用增量运算符(前缀和后缀)的不同组合,但输出结果是相同的。

int i=-3, j=2 ,k=0,m;

m=++i&&++j||++k;

printf("%d%d%d%d\n",i,j,k,m);  

I expect the output to be -2311 but it comes out to be -2301 . 我希望输出为-2311但输出为-2301

i and j are incremented because i needs to be evaluated. ij递增,因为i需要评估。 j also needs to be evaluated because i is non-zero. 由于i不为零,因此还需要评估j

But since this combined expression is non-zero, || 但是,由于此组合表达式为非零, || short-circuits, and k++ is not evaluated or executed. 短路,并且不会评估或执行k++

On the other hand, bitwise operators don't short-circuit. 另一方面,按位运算符不会短路。 They also don't convert to booleans. 它们也不会转换为布尔值。 If you want to evaluate all conditions and keep the same result you could write 如果要评估所有条件并保持相同的结果,则可以编写

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

using the double negation trick to convert integer value to boolean. 使用双重否定技巧将整数值转换为布尔值。

Or spare another statement and simplify to (courtesy from user694733): 或保留另一条语句并简化为(由user694733提供):

++i; ++j; ++k;
m = i && j || k;

The && and || &&|| operators short-circuit - depending on the value of the left-hand side of the expression, the right hand side may not be evaluated at all. 运算符短路 -根据表达式左侧的值,可能根本无法评估右侧。

For the expression a || b 对于表达式a || b a || b , if a is non-zero, then the result of a || b a || b ,如果a不为零,则a || b的结果 a || b is 1 regardless of the value of b , so b is not evaluated. a || b是1 不管b ,因此b不评估。 For the expression a && b , if a is zero, then the result of a && b is zero regardless of the value of b , so b is not evaluated. 用于表达a && b ,如果a是零,那么的结果a && b是零而不管该值的b ,因此b不评估。

In your case, the result of ++i && ++j is non-zero, so ++k is not evaluated. 在您的情况下, ++i && ++j的结果为非零,因此不会评估++k

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

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