Latest web development tutorials

C ++ comma operator

C ++ operator C ++ operator

In order to use the comma operator to string together a few expressions. Value of the entire comma expression is the value of a comma-separated list of the last expression. Essentially, the role of comma led to a series of operation is performed sequentially.

The value of the rightmost expression as the value of the entire comma expression, the value of other expressions will be discarded. E.g:

var = (count=19, incr=10, count+1);

Here, the first count assigned 19, 10 assigned to incr, then the count by one, and finally, the calculation of the right operand count result 20 + 1 is assigned var. The above expression parentheses are necessary because the comma operator is a lower priority than the assignment operator.

Try running the following examples to understand the usage of the comma operator.

#include <iostream>
using namespace std;

int main()
{
   int i, j;
   
   j = 10;
   i = (j++, j+100, 999+j);

   cout << i;
   
   return 0;
}

When the above code is compiled and executed, it produces the following results:

1010

The above program, j initial value of 10, since then increased to 11, and then coupled with the 100, the last, j plus 999, the results of 1010.

C ++ operator C ++ operator