在循环Ç多个条件 [英] Multiple conditions in for loop C

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

问题描述

我碰到这片code的。我一般都用'和;&放大器;'或'||'在单独的多个条件,循环,但这种code使用逗号做到这一点。出人意料的是,如果我改变的条件下才能输出变化。

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;        
}

输出= 2 2 2 2 2 2

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;        
}

输出= 2 2 2

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++)

这可能是也可能不是什么code的作者的意图,这取决于他的意图 - 我希望这不是生产code,因为如果编写过程序员这个希望当然preSS一个与条件之间的关系,那么这是不正确和&放大器;&安培; 运营商应该已经代替

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

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