![]() |
VOOZH | about |
In C, comma ( , ) can be used in three contexts:
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.
// 10 is assigned to i int i = (5, 10); // f1() is called (evaluated) // first followed by f2(). // The returned value of f2() is assigned to j int j = (f1(), f2());
Example 1:
15
Time Complexity: O(1)
Auxiliary Space: O(1)
Example 2:
12
Time Complexity: O(1)
Auxiliary Space: O(1)
In the above examples, we have enclosed all the operands inside the parenthesis. The reason for this is the operator precedence of the assignment operator over comma as explained below.
Consider the following expression:
x = 12, 20, 24; // Evaluation is as follows (((a = 12), 20), 24);
The main reason is that the assignment operator has high precedence over the comma operator.
Example:
Output
error: expected identifier or '(' before numeric constant
int x = 12, 20, 24;
^A comma as a separator is used to separate multiple variables in a variable declaration, and multiple arguments in a function call. It is the most common use of comma operator in C.
// comma as a separator int a = 1, b = 2; void fun(x, y);
The use of a comma as a separator should not be confused with the use of an operator. For example, in the below statement, f1() and f2() can be called in any order.
// Comma acts as a separator here // and doesn't enforce any sequence. // Therefore, either f1() or f2() // can be called first void fun(f1(), f2());
Example 1:
x = 11 x = 12 y = 12 x = 13
Time Complexity: O(1)
Auxiliary Space: O(1)
Example 2:
1 2 2 2 3 2 4 2 6 10
Time Complexity: O(1)
Auxiliary Space: O(1)
We know that in C, every statement is terminated with a semicolon but the comma operator is also used to terminate the statement after satisfying the following rules.
Example:
First Line Second Line Third Line Last line
Time Complexity: O(1)
Auxiliary Space: O(1)
There is a slight difference between a comma as a separator and a comma as an operator. Let us observe using an example:
// Wrong Method // Comma acts as separator during initialization // Will generate error int a = 4, 3; // Correct Method // Comma acts as operator int a; a = 4,3;
Now the value stored in a will be 3. Also, the following is valid,
int a =(4, 3); // value of a is 3