Comma-Separated Expressions

pradeep's Avatar author of Comma-Separated Expressions
This is an article on Comma-Separated Expressions in C.
Comma-separated expressions were inherited from C. It's likely that you use such expressions in for- and while-loops rather often. Yet, the language rules in this regard are far from being intuitive. First, let's see what a comma separated expression is.

An expression may consist of one or more sub-expressions separated by commas. For example:
Code: c
if(++x, --y, cin.isInt()) /*three expressions*/

The if condition contains three expressions separated by commas. C++ ensures that each of the expressions is evaluated and its side effects take place. However, the value of an entire comma-separated expression is only the result of the rightmost expression. Therefore, the if condition above evaluates as true only if cin.isInt() returns true. Here's another example of a comma expression:

Code: c
int j=10;
 int i=0;
 while( ++i, --j)
 {
 /*..repeat as long as j is not 0*/
 }
Contributor
22May2006,20:54   #2
Aztec's Avatar
Nice...Moderator should add this to Tips.
Go4Expert Founder
22May2006,23:05   #3
shabbir's Avatar
Quote:
Originally Posted by Aztec
Nice...Moderator should add this to Tips.
Added.
Ambitious contributor
6Mar2008,13:35   #4
rahul.mca2001's Avatar
nice......