Friday, 15 June 2018

Comma Operator inside for loop Condition in C++

You may have used Comma operator in initilialization and increment part of for loop like below

                 for(init;condition;increment) --> for(int i=0,j=5;i<j;i++,j--)


But can we used Comma operator inside for loop condition ?

The answer is Yes but it behave bit differently.

Predict the output of below program


void commaOperator()
{
    int i=0,j=0;
    cout<<"Using && inside for loop Condition"<<endl;
    for(;i<4&&j<6;)
    {
            cout<<i<<" "<<j<<endl;
            i++;
            j++;
    }
    cout<<"Using comma inside for loop Condition "<<endl;
    i=0,j=0;
    for(;i<4,j<6;)
    {
            cout<<i<<" "<<j<<endl;
            i++;
            j++;
    }

}



Output:
Using && inside for loop Condition
0 0
1 1
2 2
3 3
Using comma inside for loop Condition
0 0
1 1
2 2
3 3
4 4
5 5

As Comma operator is a binary operator it evaluates first operand but discards its result and then evaluates the second operand and returns its result.
In above example , for loop will run till second condition is true (j<6 ) and discards the first condition.

But what if we use comma operator in assignment like below
int a=5,b=7,c;
c=a,b;

Here c will be equal to a (5) as assignment has higher precedence than comma operator.


Please comment if you find anything incorrect.