CThe Comma Operator

The Comma Operator

The comma operator lets you combine two expressions, expr1, expr2, into one. Both expressions are evaluated in order, left to right, but the overall combined expression takes on the value and type of only the second one. This is a distinct, less common feature separate from the commas you already use to separate function arguments or variable declarations.

C
#include <stdio.h>

int main(void) {
    int a = (1 + 2, 3 + 4); // evaluates 1 + 2 (discarded), then 3 + 4
    printf("%d\n", a);      // 7 — the value of the second expression

    int x, y;
    y = (x = 5, x + 1); // x is set to 5, then x + 1 (6) becomes the whole expression's value
    printf("%d %d\n", x, y); // 5 6
    return 0;
}
The Common, Legitimate Use: for-Loop Headers
The comma operator's most widely accepted use is inside a for loop header, where it lets you update or initialize more than one variable per clause even though each clause is technically a single expression.

C
#include <stdio.h>

int main(void) {
    int i, j;

    for (i = 0, j = 10; i < j; i++, j--) {
        printf("i = %d, j = %d\n", i, j);
    }
    return 0;
}
Note
In for (i = 0, j = 10; ...; i++, j--), the commas inside the initialization and increment clauses are genuine comma operators chaining two expressions. This is different from the commas that separate arguments in a function call like printf("%d %d", i, j) — those are argument separators defined by function-call syntax, not the comma operator, and each argument is a separate expression with no defined evaluation order relationship enforced by a comma operator.
Rarely Useful Outside Loop Headers
Prefer separate statements outside of for loops
Outside a for header, chaining expressions with the comma operator mostly just makes code harder to read: it hides multiple actions inside what looks like a single expression, and it's easy to confuse with declaration commas ( int a, b, c;) or call-argument commas, which are not the comma operator at all. Unless you have a specific reason (such as packing multiple updates into a single macro expansion), prefer writing separate statements.

C
/* Technically legal, but harder to read than it needs to be */
int result = (printf("computing...\n"), 42);

/* Clearer as two statements */
printf("computing...\n");
int resultClear = 42;
  • expr1, expr2 evaluates both, left to right, and yields the value of expr2

  • Its main legitimate use is packing multiple updates into a for loop header, e.g. i++, j--

  • Commas separating function arguments or variable declarations are NOT the comma operator

  • Avoid the comma operator outside loop headers — it usually hurts readability