C++ Tutorial C++ Advanced C++ Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

C++ - Comma Operator

The C++ comma , operator evaluates each of its operands (from left to right) and returns the value of the last operand. This facilitates to create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions.

The comma operator has left-to-right associativity. Two expressions separated by a comma are evaluated left to right.


In the example below, the comma , operator is used to evaluate multiple expressions and returns the value of the last operand.

#include <iostream>
using namespace std;
int main () {
  int x = 10;
  int y = 10;

  //using comma operator
  int A = (x++, x);
  int B = (y+=5, y*=2, y);

  //displaying the result
  cout<<"(x++, x) : "<<A<<"\n"; 
  cout<<"(y+=5, y*=2, y) : "<<B<<"\n"; 

  return 0;

The output of the above code will be:

(x++, x) : 11
(y+=5, y*=2, y) : 30

❮ C++ - Operators