Last Updated:

Comma operator in C++

Comma operator in C++

No less interesting than the operators described above is such a C++ operator as a "comma". You've already seen several examples of its use in the for loop, where it was used to initialize several variables at once. But the comma operator can also form part of an expression. Its purpose in this case is to link several expressions in a certain way. The value of the comma-separated list of expressions is determined in this case by the value of the right-most expression. The meanings of other expressions are discarded. Therefore, the value of the expression on the right becomes the value of the entire list expression.

For example when you run this statement

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


the variable count is first assigned the number 19, the variable incr is assigned the number 10, and then one is added to the value of the variable count, after which the variable var is assigned the value of the expression on the far right, i.e. count+1, which is equal to 20. Parentheses are required here because the comma operator has a lower priority than the assignment operator.


To understand the purpose of the comma statement, let's try the following program.

#include <iostream>

using namespace std;

int main ()

{

int i, j;

j = 10;

i = (j++, j+100, 999+j);

cout << i;

return 0;

}


This program displays the number 1010. Here's why: first, the variable j is assigned the number 10, then the variable j is incremented to 11. After that, the expression j+100 is evaluated, which is not used anywhere. Finally, you add the value of the variable j (it is still 11) to the number 999, which results in the number 1010.


In fact, the purpose of the "comma" operator is to ensure the execution of a given sequence of operations. If this sequence is used on the right side of the assignment statement, the variable specified on the left side of the statement is assigned the value of the last expression in the comma-separated list of expressions. The "comma" operator in its functional load can be compared with the word "and", used in the phrase: "do this, and this, and both ...".