Search code examples
cloopssyntaxcomma-operator

What happens when there is multiple expressions in the condition part of a for loop seperated by commas?


I have an infinite loop here, but why?

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

Solution

  • The left operand of the comma operator is evaluated as a void expression, the evaluated result of a comma operator is the result of the right operand. So the "if" part of your for loop looks at the result of the printf, which is higher than zero, meaning it will never end.

    You can fix it by swapping them:

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

    But better is to not do this at all. It is not very readable.