c - 分配作为条件

标签 c visual-c++

考虑以下代码,

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/

相关文章:

c - 加载应用程序时出现访问冲突

c++ - 在 Visual Studio 2010 中使用 fuzzylite

c - sprintf 转换在格式末尾缺少类型

c - C中的寻路算法

windows - 从 Vista 上的服务使用 CreateProcessAsUser 的桌面问题

visual-c++ - 从 directshow 获取 iplImage 或 Mat 到 opencv

c++ - 在 C++17 中初始化后可以更改内联变量吗?

使用带 -fPIC 的 dlopen 和 dlsym 编译 C 程序

c - C、Pascal 和 SML 中的不相交 union

html - 通过 c/cgi-bin/html 显示密码字段和下一步按钮。我希望当屏幕显示时焦点位于密码字段中