The comma operator , in C combines two (or more) expressions, evaluating them in order from left to right and returning the value of the last expression:
int x = (f(), g()); // f() and g() are called, x == result of g()
It is most commonly used in for loops:
for(int i = 0, j = 10; i < j; ++i, --j) { ... }
When useful:
Pitfalls:
Question: What will the following code print?
int a = 1; int b = (a = 2, a + 3); printf("%d ", b);
Answer: It will print "5". First, a=2 is assigned, after which the expression a+3 evaluates to 2+3=5, and this value is assigned to variable b.
Story
In a C project, a developer used the comma operator without parentheses in a return function:
return x++, y++;It was expected that the function would return y+1, but actually return only considers the result of the expression on the right, while on the left x++ is evaluated separately. This confused the user's code, as the return result was not what was intended.
Story
In one
forloop, the programmer accidentally placed a comma instead of a semicolon:for(i=0, i<10, i++) ...The program compiled, but the loop executed only once, as the expression i<10, i++ in the
forconditions always returns the value of the last expression (i++), not the loop continuation condition.
Story
When writing macros, one developer defined:
#define DO(x, y) x, y int v = DO(f(), g());Expected both functions to be called, but forgot to put parentheses. As a result, only f() was called; the value of g() was not assigned to v. Correct usage:
#define DO(x, y) ((x), (y)).