Comma Operator in C
In this tutorial, we will understand the significance of comma operator and its functionality.
In this tutorial, we will understand the significance of comma operator and its functionality.
Comma operator is a special operator which serves two major purposes:
Let’s understand the difference between the two one by one.
We have used commas as a separator several times in our programs. We use it to declare multiple variables in the same line. The following program demonstrates this fact:
#include <stdio.h>
int main()
{
int x = 10, y = 20, z = 30;
printf("%d %d %d", x, y, z);
return 0;
}
Output:
10 20 30
In the above program, commas are used to separate three variables, x, y, and z, on the same line. Additionally, inside the printf function, commas are used to separate variables and the format string. This demonstrates how a comma can be used as a separator.
Comma can be used as an operator which works a bit differently.
Consider the following program:
#include <stdio.h>
int main()
{
int x = 5;
int y = (x++, ++x);
printf("%d", y);
return 0;
}
Can you guess the output?
The output of the above program is 7. But why?
Inside parentheses, the first operand (x++) will be evaluated first. The increment will happen, but it is not assigned to y. It means that the result of x++ is ignored. After that, ++x is evaluated and its result is assigned to y. This means y has received value 7.
Conclusion: The comma operator evaluates all of its operands, but only returns the value of the last operand.
Note that it is important to use parentheses if you want to treat the comma as an operator, because the comma operator has the lowest precedence of all operators, even lower than the assignment operator.
Consider the following program:
#include <stdio.h>
int main()
{
int x = 5;
int y = x++, ++x;
printf("%d", y);
return 0;
}
Output:
Error: expected identifier or '(' before '++' token
Because the assignment operator has a higher precedence than the comma operator, the statement y = x++ will be evaluated first. However, the compiler then expects the Lvalue of ++x, which is not available, so it throws an error.
Comma operator has the least precedence among all the operators as shown in the following table:
Precedence | Operators | Associativity |
---|---|---|
1st | () | Left to right |
2nd | Postfix increment and decrement (++, –) | Left to right |
3rd | Unary + and -, Logical negation (!), Prefix increment and decrement (++, –) | Right to left |
4th | *, /, % | Left to right |
5th | +, – | Left to right |
6th | <, <=, >, >= | Left to right |
7th | ==, != | Left to right |
8th | && | Left to right |
9th | || | Left to right |
10th | =, +=, -=, *=, /=, %=, <<=, >>=, &=, |=, ^= | Right to left |
11th | , (Comma) | Left to right |
Hey people!!!!!
Good mood and good luck to everyone!!!!!
Hey people!!!!!
Good mood and good luck to everyone!!!!!