Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comma operator in condition of loop in C

Tags:

c

comma

#include <stdio.h>

main()
{
    int i;
    for(i=0; i<0, 5; i++)
        printf("%d\n", i);
}

I am unable to understand the i<0, 5 part in the condition of the for loop.

Even if I make it i>0, 5, there's no change in output.

How does this work?

like image 426
Ravi Ojha Avatar asked Oct 18 '12 16:10

Ravi Ojha


1 Answers

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.

like image 83
Mihai Stancu Avatar answered Oct 05 '22 19:10

Mihai Stancu