The Comma Operator: Example

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

THE FOR STATEMENT (CONTINUED) ■ 101

Any of the three expressions in a for statement can be omitted, however, you must type
at least two semicolons. The shortest loop header is therefore:

Example: for(;;)

This statement causes an infinite loop, since the controlling expression is assumed to be
true if expression2 is missing. In the following

Example: for( ; expression; )

the loop header is equivalent to while(expression). The loop body is executed as


long as the test expression is true.

䊐 The Comma Operator


You can use the comma operator to include several expressions where a single expression
is syntactically correct. For example, several variables can be initialized in the loop
header of a for statement. The following syntax applies for the comma operator

Syntax: expression1, expression2 [, expression3 ...]

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

Example: 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 and is
then used to calculate and output the value of x in a single statement.
The comma operator has the lowest precedence of all operators — even lower than
the assignment operators. This means you can leave out the parentheses in the above
example.
Like any other C++ expression, an expression containing the comma operator has a
value and belongs to a certain type. The type and value are defined by the last expression
in a statement separated by commas.

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

In this example the statements in brackets are executed before the value of the product
of a * b is assigned to x.

You might also like