Home > Blogs > 30 C++ Tips in 30 Days: Tip # 9 comma separated expressions

30 C++ Tips in 30 Days: Tip # 9 comma separated expressions

By  Nov 27, 2007

Topics: Programming, C/C++

An expression may consist of one or more sub-expressions separated by commas. Such a composite expression is called a comma separated expression. Find out what it's good for and where is it used here.

The following if statement uses a comma separated expression:

if(++x, --y, cin.good()) //three subexpressions

The C++ standard guarantees that each of the expressions shall be evaluated and its side effects shall take place. However, the value of an entire comma-separated expression is only the result of the rightmost expression. Thus, the if condition evaluates as true only if cin.good() returns true. Comma separated expressions are used in loops:

int j=100;
int i=0;
while(++i, --j)
{

 /*..repeat as long as j is not 0*/
}

Comma separated expressions allow you to group multiple expressions with side-effects in a single expression.

Become an InformIT Member

Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.