-1

Can anyone help me to understand the way the condition written in the below while() loop:

Please find the code below:

int fun () {
    static int x = 5;
    x--;
    pritnf("x = %d\n", x);
    return x;
}

int main () {
  do {
    printf("Inside while\n");
  } while (1==1, fun());

  printf("Main ended\n");
  return 0;
}

Output:

Inside while
x = 4
Inside while
x = 3
Inside while
x = 2
Inside while
x = 1
Inside while
x = 0
Main ended

Also I have the below code and the output surprises:

int fun () {
    static int x = 5;
    x--;
    printf("x = %d\n", x);
    return x;
}

int main () {
  do {
    printf("Inside while\n");
  } while (fun(),1==1);

  printf("Main ended\n");
  return 0;
}

Output:


Inside while
x = 4
Inside while
x = 3
Inside while
x = 2
Inside while
x = 1
Inside while
x = 0
Inside while
x = -1
Inside while
x = -2
Inside while
x = -3

.
.
.
.

    Inside while
x = -2890
Inside while
x = -2891
Inside while
x = -2892
Inside while
x = -2893
Inside wh
Timeout

In my understanding, the condition is checked from right-to-left. If 1==1 comes on right, the condition is always true and while never breaks.

Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358
  • [Comma operator in condition of loop in C](https://stackoverflow.com/questions/12959415/comma-operator-in-conditon-of-loop-in-c) – kaylum Nov 25 '15 at 05:54
  • 3
    Possible duplicate of [comma operator in if condition](http://stackoverflow.com/questions/16475032/comma-operator-in-if-condition) – Jean-Baptiste Yunès Nov 25 '15 at 06:41

2 Answers2

6

, is an operator that takes two parameters and returns the second one.

In the first case 1==1, fun() is equivalent to fun(), so the loop happens while fun() returns a non-zero number.

In the second case, fun(), 1==1 happens forever (hence the timeout).

Blindy
  • 65,249
  • 10
  • 91
  • 131
  • I dislike the operator, its use is mostly to turn statements into expressions. GCC handled it way better, and it's completely absent from every other C++-like language (C#, Java etc) – Blindy Nov 27 '15 at 13:48
0

The comma operator is a binary operator that evaluates its first operand and discards the result, it then evaluates the second operand and returns this value.

Mohan
  • 1,871
  • 21
  • 34