Search code examples
cfor-loopcomma-operator

What does this comma do in the *test* portion of a for loop?


int c = someIntegerValue;

// Some code...

int i;
for ( i = 0; i < 5, i < c; i++ ) {
...
}

My compiler says error: expression has no effect, which sounds about right. So, which of those 2 comparisons will be used here? My guess is the i < c is ignored, but I wanted some confirmation from others as I am not in a position to run this code yet...


Solution

  • The statement

    i < 5, i < c
    

    Uses the comma operator, which evaluates all the expressions from left to right but only produces the value of the rightmost one. This means that the expression i < 5 is evaluated and discarded, while the expression i < c is evaluated and actually used by the loop.

    I assume that the author meant to write something like this:

    i < 5 && i < c
    

    which actually considers both of the expressions.

    That said, I'm not sure why this is a compiler error and not a compiler warning. This is legal code, though it's almost certainly a bug. Perhaps you have set the compiler to report errors on warnings?

    Hope this helps!