考虑以下代码,
int i;
while(i=0)
printf("Hello");
现在一般来说,i=0 是一个赋值
,而不是while
检查的条件
。
但是 GCC
编译器会发出警告,甚至会正确评估它(不执行 print 语句)。
为什么?我通常会为真值加上括号,但我的后辈们觉得我错了,这里面没有真正的括号!
编辑:消除“实际”疑问,请考虑以下测试用例
int callme(){
return 0;
}
int main(int argc,char*argv[]){
int c;
while(c = callme()){
printf("Calling...\n");
}
return 0;
}
最佳答案
表达式 i = 0
做了两件事:
- 具有将 o 存储在
i
中的副作用
- 产生值 0
I usually would do with parenthesis for the truth value but my juniors feel that i am wrong and there is no real reason for the parenthesis in this
这通常是对编译器的提示,意思是“我真的想要这个,我没有忘记 =
,闭嘴”。
对于您的特定情况,没有理由编写 if (i = 0)
:您已经知道 if (0) 的作用。但它在用作时非常有用:
if ((i = some_function()))
...
关于c - 分配作为条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10810020/