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:
if(++x, --y, cin.good()) /*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.good() returns true. Hereâs another
example of a comma expression:
Code:
int j=10;
int i=0;
while( ++i, --j)
{
/*..repeat as long as j is not 0*/
}