Comma operator

From Wikipedia, the free encyclopedia

In the C, C++, and other related programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, it then evaluates the second operand and returns this value (and type). The comma operator has the lowest precedence of any C operator, and acts as a sequence point.

The use of the comma token as an operator is distinct from its use in function calls and definitions, variable declarations, enum declarations, and similar constructs, where it acts as a separator.

int a=1, b=2, c=3, i;
 
     i=(a,b);  // stores b into i     ... operator
     i=a,b;    // stores a into i     ... separator
     i=(a+=2, a+b);// stores a+2+b == 1+2+2 into i
     i=a+=2, a+b;// stores  a+2 == 3+2 into i
     i=a,b,c;   // stores a into i
     i=(a,b,c); // stores c into i

Because the comma operator discards its first operand, it is generally only useful where the first operand has desirable side effects, such as in the initialiser or increment statement of a for loop. For example, the following terse linked list cycle detection algorithm (a version of Floyd's "tortoise and hare" algorithm):

bool loops(List *list)
{
    List *tortoise, *hare /* advances 2 times faster than tortoise */;
    for (tortoise = hare = list;
                 hare && (hare = hare->next)/* tests for valid pointers + one step of hare */;
                 tortoise = tortoise->next, hare = hare->next /* comma separates hare and tortoise step */)
        if (tortoise == hare) /* loop found */
            return true;
    return false;
}