Comma Operator in Condition of Loop in C

拥有回忆 提交于 2019-11-27 15:59:55

Comma operator evaluates i<0 Or i>0 and ignores. Hence, it's always the 5 that's present in the condition.

So it's equivalent to:

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

On topic

The comma operator will always yield the last value in the comma separated list.

Basically it's a binary operator that evaluates the left hand value but discards it, then evaluates the right hand value and returns it.

If you chain multiple of these they will eventually yield the last value in the chain.

As per anatolyg's comment, this is useful if you want to evaluate the left hand value before the right hand value (if the left hand evaluation has a desirable side effect).

For example i < (x++, x/2) would be a sane way to use that operator because you're affecting the right hand value with the repercussions of the left hand value evaluation.

http://en.wikipedia.org/wiki/Comma_operator

Sidenote: did you ever hear of this curious operator?

int x = 100;
while(x --> 0) {
    // do stuff with x
}

It's just another way of writing x-- > 0.

i<0,5 will always evaluate to 5, as always the right expression will be returned for ex1,ex2 .

The coma operator is done to the initialization and to the increment part, to do something like for(i=0,j=20;i<j;i++,j--), if you do it in the comparation part it will evaluate the last one (as it was already answered before)

The comma operator is intended for cases where the first operand has some side effects. It's just an idiom, meant to make your code more readable. It has no effect on the evaluation of the conditional.

For example,

for (i = 0; i<(i++, 5); i++) {
    // something
}

will increment i, and then check if i<5.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!