Comma Operator
The comma operator , is used to separate expressions. That means that the comma operator serves the same purpose for expressions as ; does for statements.
The comma operator has the lowest precedence of any operator in the C programming language.
What Is It Good For?
Well, not much! Most use cases for the comma operator should never be used, at it severely compromises the readability of the code.
Perform Operations On Entry To while() Loop
A use of the comma operator that can be sanctioned is when it is used to perform operations on entry to every iteration of a while() loop.
For example:
The non-comma operator way would be to do it like this:
Prevent Side-Effects In assert() Statements
Another good use is a clever manipulation of the comma operator to prevent programmers from adding side-effects to their assert statements. For example, an assert()
macro defined as:
will allow programmers to write ASSERT(x == 3)
but not ASSERT(x = 3)
. The comma operator helps achieve this (the comma operator is after the (void)(exp)
bit). For more information on this, see the C Assertions page.