Cpp - Operator Comma Operator


You can use the comma operator to include several expressions in place of a single expression.

The following syntax applies for the comma operator

expression1, expression2 [, expression3 ...] 

The expressions separated by commas are evaluated from left to right.

int x, i, limit; 
for( i=0, limit=8;  i < limit;  i += 2) 
    x = i * i,  cout << setw(10) << x; 

The comma operator separates the assignments for the variables i and limit.

The comma operator has the lowest precedence of all operators - even lower than the assignment operators.

An expression containing the comma operator has a value of certain type.

The type and value are defined by the last expression in a statement separated by commas.

x = (a = 3, b = 5, a * b); 

In the code above the statements in brackets are executed and the value of the product of a * b is assigned to x.