Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
operator
communitycreator

What is the built-in comma operator in C++?

Danil

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The comma operator evaluates all of its operands from left to right and returns the value of the last one.

Syntax

expr1, expr2, expr3...

Where expr1, expr2, expr3... is one or more expressions, the last of which is returned as the value of the comma operator expression.

Code

#include <iostream>
int main() {
int n = 1;
int m = (
++n, // n = n + 1 = 1 + 1 = 2
std::cout << "n = " << n << '\n', // Displays "n = 2"
++n, // n = n + 1 = 2 + 1 = 3
2 * n // 2 * 3 = 6
); // The operands are executed sequentially,
// the result of the last expression is assigned
// to a variable: 2 * n = 2 * 3 = 6
std::cout << (++m, m); // First operand evaluates
// and its result is discarded,
// expression evaluates to
// 7
}

RELATED TAGS

c++
operator
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring