English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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.
In essence, the comma operator is used to execute a series of operations in order.
The value of the expression on the rightmost side will be the value of the entire comma expression, and the values of the other expressions will be discarded. For example:
var = (count=19, incr=10, count+1;
Here, first assign the value of count to 19Then assign the value of incr to 10Then add count 1Finally, assign the value of the expression on the rightmost side to count+1 The result of the calculation 20 Assign to var. The parentheses in the above expression are necessary because the precedence of the comma operator is lower than that of the assignment operator.
尝试运行以下示例,以理解逗号运算符的用法。
#include <iostream> using namespace std; int main() { int i, j; j = 10; i = (j++, j+100, 999+j); cout << i; 返回 0; }
当上面的代码被编译和执行时,它会产生以下结果:
1010
上面的程序中,j 最初的值为 10,然后自增到 11,接着再加上 100,最后 j 再加上 999,得出结果 1010。