Course contentsShow
← C
Lesson 224 of 1,2193. Operators and ExpressionsFree lesson

The comma operator `,`

The comma operator ,

What you'll learn: How to use the comma operator to evaluate multiple expressions in a single statement while controlling which result is kept.

Multitasking in a single line

In C, the comma isn't just for separating variables in a list; it is an actual operator. The comma operator allows you to string together several expressions where the language normally only expects one.

Think of it like a relay race. A runner (an expression) completes their lap, performs their action, and then hands the baton to the next runner. While every runner participates, only the very last person to cross the finish line determines the final result of the race.

How it works

When C encounters a comma operator, it follows a strict two-step rule:

  1. It evaluates the expression on the left first. This usually involves a "side effect," such as changing the value of a variable.
  2. It discards the result of the left expression, moves past a sequence point, and evaluates the expression on the right.

The entire operation then "returns" the value of the rightmost expression.

#include <stdio.h>

int main() {
    int a = 1, b = 2, result;

    // The comma operator at work
    // 1. a is incremented (side effect)
    // 2. The sum (a + b) is calculated
    // 3. 'result' gets the value of the final expression
    result = (a++, a + b); 

    printf("a: %d, result: %d", a, result); 
    // Output: a: 2, result: 4
    
    return 0;
}

Why use it?

You won’t see the comma operator everywhere, but it is a specialist tool. Its most common home is inside for loops. If you need to increment two different counters at the same time, the comma operator allows you to pack both actions into the single "update" slot of the loop header: for(i = 0, j = 10; i < j; i++, j--).

It keeps your code compact by ensuring that related side effects happen together before the next sequence point, without needing to wrap every tiny action in a new set of curly braces.

Key takeaway

The comma operator executes multiple expressions from left to right and results in the value of the very last expression.