2

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.

Dan Cornilescu
  • 39,470
  • 12
  • 57
  • 97
ThinkingC
  • 21
  • 3

2 Answers2

6

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.

Paul Kienitz
  • 878
  • 6
  • 25
1

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.

Jack
  • 131,802
  • 30
  • 241
  • 343