Guys when I attended a C quiz online, I came across a statement while(s++,6);
where s is initialized to zero. I don't know what the while loop will exactly do when there is a comma operator in between. When I ran it on my gcc compiler it ran with no output. But when I changed the while condition as while(1,s++)
it returned s value as 1. Can anyone tell me what is happening at that while.

- 39,470
- 12
- 57
- 97

- 21
- 3
-
http://www.mindtribe.com/2011/07/forgotten-c-the-comma-operator/ – Dair Oct 25 '15 at 01:59
-
see [What does the comma operator `,` do in C?](http://stackoverflow.com/a/18444099/1708801) – Shafik Yaghmour Oct 25 '15 at 02:00
2 Answers
The comma operator evaluates the left side and then throws away the result. The while condition keeps looping for any value other than zero. The first will be an infinite loop; the second will increment s and then stop.
I suspect in this case the comma was a typo and they meant to type a less-than.

- 878
- 6
- 25
-
1˖1 for a brilliant guess at how this code came to be – R.. GitHub STOP HELPING ICE Oct 25 '15 at 02:10
From C11 standard §6.5.17:
The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; the result has its type and value.
This means that 1,s++
evaluates 1
(so nothing happens), then it evaluates s++
and returns the result of that expression only.
So that's expression is equivalent to while (s++)
. If the left-hand side of a comma expression doesn't have any side effects, like in your situation, then you can remove it.

- 131,802
- 30
- 241
- 343