Jump to content

Comma operator: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
No edit summary
No edit summary
Line 1: Line 1:
{{Mergeto|Operators in C and C++|date=July 2007}}

In the [[C programming language|C]], [[C++]], and other related programming languages, the '''comma operator''' (represented by the [[token]] <code>,</code>) 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]].
In the [[C programming language|C]], [[C++]], and other related programming languages, the '''comma operator''' (represented by the [[token]] <code>,</code>) 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]].



Revision as of 19:18, 14 February 2008

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.

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 *l1, *l2;
    for (l1 = l2 = list; l2 && (l2 = l2->next); l1 = l1->next, l2 = l2->next)
        if (l1 == l2)
            return true;
    return false;
}