Easy Tutorial
❮ Cpp Environment Setup Cpp Passing Pointers To Functions ❯

C++ Comma Operator

C++ Operators

Using the comma operator is to group several expressions together.

The value of the entire comma expression is the value of the last expression in the series.

Essentially, the comma operator is used to sequence operations.

expression1, expression2

The evaluation process is: first evaluate expression1, then evaluate expression2. The value of the entire comma expression is the value of expression2.

The value of the rightmost expression will be the value of the entire comma expression, while the values of the other expressions will be discarded.

For example:

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

Here, count is first assigned the value 19, incr is assigned the value 10, then count is incremented by 1, and finally, the result of the rightmost expression count+1, which is 20, is assigned to var. The parentheses in the expression are necessary because the precedence of the comma operator is lower than that of the assignment operator.

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

Example

#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 result:

1010

In the above program, j is initially 10, then it increments to 11. At this point, j is 11, then the second expression j+100 is calculated, and finally, j (which is 11) is added to 999. Thus, i is assigned the value of the last expression, which is 999 + j, or 999 + 11 = 1010.

C++ Operators

❮ Cpp Environment Setup Cpp Passing Pointers To Functions ❯