Multiple Conditions in C 'for' loop


Multiple conditions should be joined with logical operators (&& , ||), else it would be bad code practice.

Example 1 

#include <stdio.h>

int main(void)  
{
  int i, j;
  for(i=0, j=2; j>=0, i<=5; i++, j--)
  {
       printf("%d ", i+j);
  }
  return 0;        
}


Output:
1
2 2 2 2 2 2 

It ignores the first condition and honors only the second condition.

In some compiler, we might get the below error

error: left-hand operand of comma expression has no effect   [-Werror=unused-value]                     


Example 2 

#include <stdio.h>

int main(void)  
{
  int i, j;
  for(i=0, j=2; j>=0 && i<=5; i++, j--)
  {
       printf("%d ", i+j);
  }
  return 0;        
}

Output:
1
2 2 2 






Comments