Comma as an operator
A comma operator in C++ is a binary operator. It evaluates the first operand & discards the result, evaluates the second operand & returns the value as a result. It has the lowest precedence among all C++ Operators. It is left-associative & acts as a sequence point.
Syntax:
data_type variable = (value1, value2);
Example 1:
C++
// C++ program to demonstrate // comma as a operator #include <iostream> using namespace std; int main() { // comma as a operator int num = (24, 78, 85); cout << num << endl; return 0; } |
85
As we can see, the values 24,78, and 85 have been enclosed in the parenthesis. This is because the assignment operator has higher precedence than the comma operator so if we don’t use parenthesis, we will encounter an error as the compiler will treat integer values 78 and 85 as an identifier in variable declaration according to C++ syntax. Let’s understand this with the help of the following example.
Example 2:
C++
// C++ program to demonstrate // comma as a operator #include <iostream> using namespace std; int main() { // Assignment Operator int num1 = 10, 24, 30; // Commma as a Operator int num2 = (10, 24, 30); cout << num1 << endl; cout << num2 << endl; return 0; } |
Output
error: expected unqualified-id before numeric constant int num1 = 10, 24, 30; ^
Comma in C++
Comma (,) in C++ can work in three different contexts:
- Comma as an operator
- Comma as a separator
- Comma operator in place of a semicolon
Contact Us