Comma in C
— 417 words — 3 min
Do you know what this C code produces?
int
This code does not print “hello”. When the comma is used in such a
case it acts as binary operator. This means the condition in the if
statement is evaluated as follows:
- evaluate the first expression and discard the result. In this case the
evaluation is only
1ortrueand the result is discarded. - evaluate the second expression and return the result. In this case,
it’s
0which is equal tofalseand this result is returned. - That result is used in the if condition and, therefore, it evaluates to false.
You could use more than two expressions separated by a comma. In
general, the expressions are elevated from left to right and the
rightmost result is returned. If you do this and you turn on
-Wunused-value (or -Wall for that matter), your compiler will tell
you about this.
$ gcc -Wall main.c && ./a.out
main.c: In function ‘main’:
main.c:3:14: warning: left-hand operand of comma expression has no effect [-Wunused-value]
3 | if (1,0)
| ^
You can use this in variable initialization as well.
// number would be 42. The number 22 is just discarded.
int number = ;
Or call functions:
// return 1 on success
int
int
int
Executing the above program results in this output.
$ gcc main.c && ./a.out
log: call_grandma()
answer=42
Other more common uses that you probably know are the comma as a separator, for example
- while assigning values to multiple variables like
int a=21, b=42; - in a function call:
do_stuff(get_arg1(), get_arg2()). Note that the comma only acts as separator and as far as I know, we don’t know whetherget_arg1()is called beforeget_arg2(). I’m not sure whether the compiler decides based on optimization purposes or if there is other reasoning how to deal with this. If you know more about this, please tell me. - in a
forloop:for (int a=0, b=42; a<10; a++) {}
Sometimes, the comma can also be used in place of a semicolon.
int
Yes, this works.
You can find more examples and some more detailed explanations on GeeksForGeeks.
Articles from blogs I follow around the net
Resetting Mutt's terminal after OAuth2 / GPG
A quick fix for how to get mutt's terminal reset after shelling out to GPG during the OAuth2 flow.
via Signs of Triviality March 31, 2026Status update, February 2026
Hi all! Lars has contributed an implementation independent test suite for the scfg configuration file format. This is quite nice for implementors, they get a base test suite for free. I’ve added support for it for libscfg, the C implementation. I’ve spent some…
via emersion February 22, 2026Generated by openring