C - Comma operator


1. The comma operator(,) is used with the for statement. This operator permits two different expressions to appear in situations where only one expression would ordinarily be used.

2. For example, it is possible to write
for(expression la, expression lb; expression 2;expression 3) statement
where expression la and expression lb are the two expressions, separated by the comma operator. These two expressions would typically initialize two separate indices that would be used simultaneously within the for loop.

3. Similarly a for statement might make use of the comma operator in the following manner:
for(expression1;expression2;expression 3a, expression 3b) statement
Here expression 3a and 3b, separated by the comma operator, appear in place of the usual single expression.

4. In this application the two separate expressions would typically be used to alter (eg. increment or decrement) the two different indices used simultaneously within the loop. For example, one index might count forward while the other counts backward.)

5. Also a statement like
for(expression la, expression lb; expression 2;expression 3a, expression 3b)
statement is valid. However a statement like
for(expression I; expression 2a, expression 2b,expression 3)
statement is invalid.
This is because two condition can be combined either by using logical or(||) or logical and(&&). They cannot be combined using a comma operator.


  • Print Page