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

The comma operator in `for` loops

The comma operator in for loops

What you'll learn: How to manage multiple variables within a single loop header using the comma operator.

The multi-tasking loop

Usually, a for loop handles one variable, like a counter that goes from 1 to 10. But sometimes, you need to juggle two things at once. Imagine two runners on a track starting at opposite ends and running toward each other. You need to track both of their positions simultaneously in every step of the loop.

In C, the comma operator (,) allows you to squeeze multiple expressions into the parts of the for loop where usually only one is expected.

How it works

A standard for loop has three sections: initialization, condition, and increment. The comma operator lets you perform multiple actions in the initialization and increment sections.

When C sees a comma in these sections, it says, "Do the first thing, then do the next thing."

#include <stdio.h>

int main() {
    int i, j;
    int max = 5;

    // We initialize BOTH i and j, and increment BOTH i and j
    for (i = 0, j = max; i <= max; i++, j--) {
        printf("i is %d, j is %d\n", i, j);
    }

    return 0;
}

In the example above:

  1. Initialization (i = 0, j = max): Before the loop starts, we set i to 0 and j to 5 at the same time.
  2. Condition (i <= max): The loop checks only this middle part to decide whether to keep going. (Note: You rarely use commas in the condition section).
  3. Increment (i++, j--): At the end of every lap, i goes up by one and j goes down by one.

Why use it?

You could technically declare j outside the loop and decrease it manually inside the loop body. However, using the comma operator keeps the "loop logic" all in one place. It makes it clear to anyone reading your code that i and j are linked partners in this specific process.

Think of it like a choreographer: the for loop header is the script that tells both dancers exactly where to start and how to move in sync, rather than shouting instructions to one dancer from the sidelines.

Key takeaway

The comma operator lets you initialize and update multiple variables inside a for loop header, keeping your control logic clean and synchronized.