Comma Operator

Article by:
Date Published:
Last Modified:


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:

char * rxBuffer;
while(getData(rxBuffer), strlen(rxBuffer) > 0) {
    // Process characters in rxBuffer here
    // ...

The non-comma operator way would be to do it like this:

char * rxBuffer;
while(strlen(rxBuffer) > 0) {
    // Process characters in rxBuffer here
    // ...


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:

#define ASSERT(exp)  ((void)(exp), (exp ? : AssertFailed(__FILE__, __LINE__, #exp)))

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.




comments powered by Disqus