🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Comma Operator in Loops
A free C tutorial on running two loop variables together, with palindrome checking, evaluation order, and the traps every embedded C programmer should avoid.
In this lecture of our free C tutorial and free embedded C course, we meet a small operator with big consequences: the comma. Inside a for header it lets you initialise and update more than one variable at once. This is the trick behind buffer reversal, string comparison, and two-pointer scans that you will write again and again in embedded C programming.
What You Will Learn
- What the comma operator does and what value it produces.
- How to initialise and update several variables in one
forheader. - Why only the right-most expression decides the loop condition.
- How the comma operator differs from the comma that separates function arguments or declarations.
- A complete palindrome checker built with two converging indexes.
- Typical mistakes, style rules, and a note on readability in firmware code.
Prerequisites
Finish the previous lecture on optional for expressions first. You should also know basic arrays and strings, because the main example walks through the characters of a word.
What Is the Comma Operator?
The comma operator joins two expressions into one. The left expression is evaluated first and its value is thrown away. Then the right expression is evaluated, and that value becomes the value of the whole comma expression. A sequence point sits between the two, so the order is guaranteed, unlike many other places in C.
#include <stdio.h>
int main(void)
{
int a = 0, b = 0;
int x = (a = 4, b = 9, a + b); /* value of last expression */
printf("x = %d, a = %d, b = %d\n", x, a, b);
return 0;
}
$ gcc -std=c17 -Wall -Wextra -o commaval commaval.c
$ ./commaval
x = 13, a = 4, b = 9
Both assignments happened, left to right, and the final sum became the result stored in x. The parentheses are necessary here, because the comma has the lowest precedence of all C operators and would otherwise be read as a separator in the declaration.
Comma Operator Inside a For Loop
The for header has three slots but each slot holds one expression. When a task needs two changes at the same moment, the comma operator fits two expressions into one slot. Both the initialiser and the update slot are normal places for it.
for (i = 0, j = 10; i <= j; i++, j--)
Here i climbs while j falls, and the loop stops when they cross. This is exactly the shape used by algorithms that work from both ends of a buffer toward the middle.
| Slot | Example with comma | Effect |
|---|---|---|
| init | i = 0, j = 10 | Both variables prepared before the first test |
| test | i < j | One condition, no comma needed |
| update | i++, j– | Both variables move after every pass |
Declaring Two Variables in the Header
Since C99 you may declare variables in the first slot. A declaration uses a comma as a separator, not as an operator, so both variables must have the same type: for (size_t lo = 0, hi = len - 1; lo < hi; lo++, hi--). You cannot declare an int and a char together this way.
Worked Example: Palindrome Checker
A palindrome reads the same in both directions, such as “level”. The idea is simple. Put one index at the first letter and one at the last, compare them, and move both inward. If any pair differs the word is not a palindrome.
#include <stdio.h>
#include <string.h>
int main(void)
{
const char *word = "level";
size_t len = strlen(word);
int ok = 1;
for (size_t lo = 0, hi = len - 1; lo < hi; lo++, hi--)
{
printf("compare word[%zu]='%c' with word[%zu]='%c'\n",
lo, word[lo], hi, word[hi]);
if (word[lo] != word[hi])
{
ok = 0;
break;
}
}
printf("%s is %sa palindrome\n", word, ok ? "" : "not ");
return 0;
}
$ gcc -std=c17 -Wall -Wextra -o comma comma.c
$ ./comma
compare word[0]='l' with word[4]='l'
compare word[1]='e' with word[3]='e'
level is a palindrome
Only two comparisons were needed for a five-letter word, because the middle letter always matches itself. The loop does half the work of a one-index approach, which matters when you scan a large receive buffer on a small microcontroller. One caution: if the string is empty, len - 1 wraps around because size_t is unsigned. A real function should check len == 0 first.
Only the Last Expression Counts in a Condition
Now the classic trap. If you put a comma expression in the test slot, every expression runs but only the right-most one decides whether the loop continues. The following program shows it.
#include <stdio.h>
int main(void)
{
int up, down;
/* only the right-most expression decides the condition */
for (up = 0, down = 3; up < 10, down > 0; up++, down--)
printf("up=%d down=%d\n", up, down);
return 0;
}
$ gcc -std=c17 -Wall -Wextra -o commaval2 commaval2.c
commaval2.c: warning: left-hand operand of comma expression has no effect [-Wunused-value]
$ ./commaval2
up=0 down=3
up=1 down=2
up=2 down=1
The test up < 10 is always true here, and it is ignored. Only down > 0 ends the loop. If you really mean both, write up < 10 && down > 0. GCC even warns you, which is one more reason to compile with warnings enabled.
Comma Operator vs Comma Separator
| Where | Is it the operator? | Order guaranteed? |
|---|---|---|
| x = (a = 1, b = 2); | Yes | Yes, left to right |
| int a = 1, b = 2; | No, declaration separator | Not applicable |
| f(a, b) | No, argument separator | No, arguments may be evaluated in any order |
| for (i = 0, j = 5; …; i++, j–) | Yes | Yes |
Never rely on a particular evaluation order of function arguments. Writing f(i++, i++) is undefined behaviour, and the comma between arguments does not help.
Real-World Uses in Embedded C
- Buffer reversal: swap bytes from both ends when converting between little and big endian packets.
- Ring buffer indexes: advance a read index and a write index together in test code.
- Matching received frames: compare a header from the front and a checksum from the back.
- Polling with a timeout:
for (retries = 0, ready = 0; !ready && retries < 100; retries++)keeps the state variables together.
Common Mistakes and Troubleshooting
- Comma in the condition. Only the last expression is used. Use
&&or||instead. - Mixing types in a declaration.
for (int i = 0, char c = 'a'; ...)is invalid. - Unsigned underflow.
hi = len - 1breaks for an empty string. - Too many things in the header. If you need three or more variables, use a normal loop with statements in the body.
Best Practices
- Use the comma operator in
forheaders only for initialising and updating loop variables. - Avoid it elsewhere. Coding standards such as MISRA C discourage it in ordinary expressions.
- Choose names like
loandhiorheadandtailso the reader sees the intent. - Always enable
-Wall -Wextraso unused left-hand operands are reported.
Summary and Key Takeaways
- The comma operator evaluates left to right and returns the right-most value.
- In a
forheader it allows several variables to be initialised and updated together. - In the condition slot, every part runs but only the last one controls the loop.
- Commas in declarations and function arguments are separators, not operators.
You now have a second tool for loops, ready for the nested-loop patterns in the next lecture of this free C programming course for embedded systems.
Frequently Asked Questions
What does the comma operator return in C?
It returns the value of the right-most expression, after evaluating all the expressions from left to right.
Can I use two conditions separated by a comma in a for loop?
You can write it, but only the last condition controls the loop. Use the logical AND or OR operators to combine conditions.
Is the comma in int a, b; an operator?
No. It is a declaration separator. The comma operator only appears in expressions.
Why is the comma operator discouraged outside for loops?
It makes code harder to read and can hide mistakes. Separate statements are clearer and easier to debug.
Is the order of evaluation guaranteed with a comma?
Yes for the comma operator, because there is a sequence point after the left operand. It is not guaranteed for function arguments.
Keep Going With the Free Embedded C Course
Next up: nested loops, star patterns, multiplication tables, and a keypad scan, all inside the free C programming course on EmbeddedPathashala.

2 Comments