C++ Comma Operator

C++ Operators

The comma operator is used to put several expressions together.

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

Essentially, the comma operator serves to execute a series of operations in order.

表达式1, 表达式2

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

The value of the rightmost expression serves as the value of the entire comma expression, and the values of the other expressions are discarded.

For example:

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

Here, first assign count to 19, assign incr to 10, then add 1 to count, and finally assign the result 20 of the rightmost expression count+1 to var. The parentheses in the above expression are necessary because the comma operator has lower precedence than 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 results:

1010

In the above program, the initial value of j is 10, then it increments to 11, at which point the value of j is 11. Then the second expression j+100 is evaluated, and finally j (where j is 11) plus 999 is computed. In the end, i is the value of the last expression 999+j, that is, 999+11=1010.

C++ Operators

other extensions