I have the following code source in C:
#include<stdio.h>
void main()
{
int i=0, x=3;
while((x---1))
{
i++;
}
printf("%d", i);
}
How does this while statement work and why does it print 2 instead of 1?
I have the following code source in C:
#include<stdio.h>
void main()
{
int i=0, x=3;
while((x---1))
{
i++;
}
printf("%d", i);
}
How does this while statement work and why does it print 2 instead of 1?
因为x---1is 真的x-- - 1会产生x - 1before decrementing的值x。
鉴于x初始值为 3,循环运行 2 次(一次 x = 3,一次 x = 2,然后下一次 x 为 1,因此x - 1为 0,循环不再运行)。
所以,i从 0 开始,它增加了两次,所以它最终是 2。
(x---1) ==(x-- -1)
因为编译器首先尝试选择更大的标记,所以---解释为--&-
表达式x-- - 1意味着首先从当前值中1 减去x由于-减法运算。然后 由于后缀减运算符,x值减--1 。
例如在第一次迭代之前x = 3,所以 while 条件是2(即3 - 1)在x减少之后,并且在下一次迭代之前x = 2。
x = 3, i =0;
while(2) , 和 in 循环i变为 1 x = 2,i = 1;
while(1) , 和 in 循环i变为 2x = 1,i = 2;
x - 1=0给出 while(0)循环中断而i不是递增。 所以在循环输出之后i: 2
再注意一点: i不会因为循环中断而增加,因为i++在 while-block{}中,而是x减少到0. 如果你 printf 循环之后,x那么输出将是0.
所以如果你用更多的空格来看待它,while 可能更有意义:
while( ( x-- - 1) )
它使用后减量,所以 x 在返回它的当前值后被修改,所以它真的等同于:
while( ( x - 1) )
并且循环将一直运行,直到表达式为falseor 在这种情况下0相当于false. 所以运行是这样的:
x x - 1 i
=============
3 2 1 x - 1 not 0 so increment i
2 1 2 x - 1 not 0 so increment i
1 0 2 Loop exits here and does not increment i again
此时循环退出,您点击printf.
while((x---1))相当于while((x-- -1 != 0)),这又与写作 相同while(x-- != 1)。由于 的值x--是减量x 前的值,因此与
while(x != 1) {
x--;
...
}
x如果从 3 开始运行两次。