Comma Operator

Article by:
Date Published:
Last Modified:

Overview

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:

1
2
3
4
5
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:

1
2
3
4
5
6
7
8
char * rxBuffer;
GetData(rxBuffer);
while(strlen(rxBuffer) > 0) {
    // Process characters in rxBuffer here
    // ...

    GetData(rxBuffer);
}

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:

1
#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.


Authors

Geoffrey Hunter

Dude making stuff.

Creative Commons License
This work is licensed under a Creative Commons Attribution 4.0 International License .

Tags

    comments powered by Disqus