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*/
 }
0
Aztec's Avatar, Join Date: May 2006
Contributor
Nice...Moderator should add this to Tips.
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Quote:
Originally Posted by Aztec
Nice...Moderator should add this to Tips.
Added.
0
rahul.mca2001's Avatar, Join Date: Feb 2008
Ambitious contributor
nice......