Search code examples
cwhile-loopprogramming-languagescomma-operator

C Programming - comma operator within while loop


Prog 1:

#include<stdio.h>
 int main()
 {
     int i=0;
     while(i<=8,i++);
     printf("%d",i);
     return 0;
  }

Prog 2:

#include<stdio.h>
 int main()
{
  int i=0;
  while(i++,i<=8);
  printf("%d",i);
  return 0;
}

The output of Prog 1 is 1 and that of Prog 2 is 9.

Can someone explain whats going here. How the two codes are different?


Solution

  • The comma operator evaluates both of its arguments in turn, throwing away the result, except for the last. The last evaluated expression determines the result of the entire expression.

    i<=8,i++ - here the value of the expression is the value of i++, which is the value of i before being incremented. It's 0 so the loop immediately terminates.

    i++,i<=8 - here the value of the expression is the value of i<=8 which is 0 only when i is incremented to 9.

    On a personal note: I think the second form, while somewhat comparable to a for loop, is less clear to the reader of the code than an actual for loop.