Table of Contents
The comma operator (,) evaluates two or more expressions from left to right and returns the value of the last expression. Each expression is evaluated completely before the next expression is evaluated.
Although the comma operator can combine multiple expressions into a single statement, it is used less frequently in modern C++ because separate statements are generally easier to read. It is still commonly encountered in for loops and certain compact expressions.
Source Code #
#include <iostream>
int main()
{
int a = 10;
int b = 20;
int result = (a += 5, b += 10, a + b);
std::cout << "Value of a : " << a << '\n';
std::cout << "Value of b : " << b << '\n';
std::cout << "Result : " << result << '\n';
return 0;
}
Output #
Value of a : 15
Value of b : 30
Result : 45
Explanation #
- The comma operator (
,) evaluates multiple expressions from left to right. - Each expression is evaluated completely before the next expression begins.
a += 5updates the value ofafrom10to15.b += 10updates the value ofbfrom20to30.- The final expression
a + bevaluates to45. - The value of the last expression becomes the result of the entire comma expression and is assigned to
result. - The comma operator is commonly used in
forloop expressions and other situations where multiple operations are required in a single expression. return 0;terminates the program successfully.