分配作为条件 [英] assignment works as a condition

查看:24
本文介绍了分配作为条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的代码,

int i;
while(i=0)
    printf("Hello");

现在一般来说 i=0 是一个 assignment 而不是 conditionwhile 检查.但是 GCC 编译器让它发出警告,甚至正确评估它(不执行打印语句).

Now Generally speaking i=0 is an assignment and not a condition for while to check. But the GCC compiler lets it go with a warning and even evaluates it correctly (does not execute the print statement).

为什么?为了真值,我通常会用括号做,但我的后辈觉得我错了,括号里没有真正的理由!

Why? 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!

将实际"疑问归零,请考虑以下测试用例

Zeroing down on the 'actual' doubt, Please consider the following test case

int callme(){
    return 0;
}

int main(int argc,char*argv[]){
    int c;
    while(c = callme()){
        printf("Calling...\n"); 
    }
    return 0;    
}

推荐答案

表达式 i = 0 做了两件事:

The expression i = 0 does 2 things:

  • 有在i
  • 中存储o的副作用
  • 产生值 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

这通常是对编译器的一个提示,意思是我真的想要这个,我没有忘记 =,闭嘴".

It's usually a hint to the compiler meaning "I actually want this, I didn't forget a =, shut up".

对于您的特定情况,没有理由编写 if (i = 0):您已经知道 if (0) 的作用.但是当用作:

For your specific case there's no reason to write if (i = 0): you already know what if (0) does. But it's pretty useful when used as:

if ((i = some_function()))
    ...

这篇关于分配作为条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆