C'for'循环中的多个条件 [英] Multiple conditions in a C 'for' loop

查看:350
本文介绍了C'for'循环中的多个条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我碰到这段代码。我通常使用'&'或'||'来为循环分隔中的多个条件,但是这个代码使用逗号来完成这个操作。



令人惊讶的是,如果我改变了条件的顺序,输出就会变化。

 #include< ; stdio.h中> 

int main(){
int i,j = 2; (i = 0; j> = 0,i< = 5; i ++)
{
printf(%d,i + j)
j--;
}
return 0;

$ / code $ / pre
$ b $输出= 2 2 2 2 2 2

 #include  

int main(){
int i,j = 2; (i = 0; i <= 5,j> = 0; i ++)
{
printf(%d,i + j)的


j--;
}
return 0;

$ / code>

输出= 2 2 2



有人可以解释一下原因吗?它看起来只是检查最后一个逗号分隔的条件。

解决方案

逗号运算符评估它的所有操作数并得到最后一个。因此,基本上无论你先写什么样的条件,都会被忽略,第二个只会是显着的。

<$对于(i = 0; j> = 0,i≤5; i ++)

$ b,p $ p> 因此,
$ b

对于(i = 0; i <= 5; i ++)而言与

 

这可能是也可能不是代码的作者的意图,取决于他的意图 - 我希望这不是生产代码,因为如果写这个的程序员想要表达条件之间的AND关系,那么这是不正确的,而且&& 操作符应该有被用来代替。


I came across this piece of code. I generally use '&&' or '||' to separate multiple conditions in a for loop, but this code uses commas to do that.

Surprisingly, if I change the order of the conditions the output varies.

#include<stdio.h>

int main() {
    int i, j=2;

    for(i=0; j>=0,i<=5; i++)
    {
         printf("%d ", i+j);
         j--;
    }
    return 0;
}

Output = 2 2 2 2 2 2

#include<stdio.h>

int main(){
    int i, j=2;

    for(i=0; i<=5,j>=0; i++)
    {
         printf("%d ", i+j);
         j--;
    }
    return 0;
}

Output = 2 2 2

Can somebody explain the reason? It seems to be checking only the last comma-separated condition.

解决方案

The comma operator evaluates all its operands and yields the value of the last one. So basically whichever condition you write first, it will be disregarded, and the second one will be significant only.

for (i = 0; j >= 0, i <= 5; i++)

is thus equivalent with

for (i = 0; i <= 5; i++)

which may or may not be what the author of the code intended, depending on his intents - I hope this is not production code, because if the programmer having written this wanted to express an AND relation between the conditions, then this is incorrect and the && operator should have been used instead.

这篇关于C'for'循环中的多个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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