C++ Comma Operator
The comma operator is used to group several expressions together.
The value of the entire comma expression is the value of the last expression in the series.
Essentially, the role of the comma is to execute a sequence of operations in order.
表达式1, 表达式2
The evaluation process is: first evaluate expression 1, then expression 2. The value of the entire comma expression is the value of expression 2.
The value of the rightmost expression becomes the value of the whole comma expression; the values of the other expressions are discarded.
For example:
var = (count=19, incr=10, count+1);
Here, count is first assigned 19, incr is assigned 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 above are necessary because the comma operator has lower precedence than the assignment operator.
Try running the example below 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 code above is compiled and executed, it produces the following result:
1010
In the program above, j is initially 10, then increments to 11, so j's value is 11; then the second expression j+100 is evaluated, and finally j (which is 11) is added to 999, so i becomes the value of the last expression, 999+j, i.e. 999+11=1010.
C++ Operators