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
1. 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.
data_type variable = (value1, value2);
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.
error: expected unqualified-id before numeric constant int num1 = 10, 24, 30; ^
2. Comma as a separator
A comma as a separator is used in multiple variable declarations and multiple arguments in a function call.
data_type var_name1, var_name2; //in variable declaration function_call(argument_1, argument_2); // in function call
34 45 65
In the above program, we declare multiple variables declarations in a single line as separated by a comma. A comma acts here as a separator, not an operator.
Another example of multiple arguments is in a function call, where we used commas as a separator.
In the main() function, add() function is called where we used a comma to separate multiple arguments.
3. Comma Operator in Place of a Semicolon
The comma operator in C++ can be also used for terminating statements of the C++ Program. To use a comma operator in place of a semicolon, the following conditions must be satisfied.
- The variable declaration statements must be terminated with a semicolon.
- The statements after the declaration statement can be terminated by the comma operator.
- The last statement of the program must be terminated by a semicolon.
54 34 45
In the above program all the variable declarations num1, num2 & num3 are ended with semicolons and the last statement of output is ended with a semicolon.
Please Login to comment...