任何人都可以帮助我理解以下 while()
循环中的条件编写方式:
请找到下面的代码:
int fun () {
static int x = 5;
x--;
pritnf("x = %d\n", x);
return x;
}
int main () {
do {
printf("Inside while\n");
} while (1==1, fun());
printf("Main ended\n");
return 0;
}
Output:
Inside while
x = 4
Inside while
x = 3
Inside while
x = 2
Inside while
x = 1
Inside while
x = 0
Main ended
我还有以下代码和令人惊讶的输出:
int fun () {
static int x = 5;
x--;
printf("x = %d\n", x);
return x;
}
int main () {
do {
printf("Inside while\n");
} while (fun(),1==1);
printf("Main ended\n");
return 0;
}
Output:
Inside while
x = 4
Inside while
x = 3
Inside while
x = 2
Inside while
x = 1
Inside while
x = 0
Inside while
x = -1
Inside while
x = -2
Inside while
x = -3
.
.
.
.
Inside while
x = -2890
Inside while
x = -2891
Inside while
x = -2892
Inside while
x = -2893
Inside wh
Timeout
根据我的理解,条件是从右到左检查的。如果 1==1 出现在右侧,则条件始终为 true,并且 while 永远不会中断。
最佳答案
,
是一个运算符,它接受两个参数并返回第二个参数。
在第一种情况1==1,fun()
相当于fun()
,因此循环发生在fun()
> 返回一个非零数字。
在第二种情况下,fun(), 1==1
永远发生(因此超时)。
关于c - 奇怪的 while() 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33909325/