The comma (,) in C is a special symbol that can be used in different ways within a program. It helps separate expressions, variables, and statements while improving code flexibility.
- Comma as an Operator: Evaluates multiple expressions from left to right and returns the value of the last expression.
- Comma as a Separator: Separates variables, function arguments, or declarations within a statement.
- Comma in Place of a Semicolon: Multiple expressions can be written in a single statement using the comma operator.
Example: In int a = (x = 5, y = 10, x + y);, all expressions are evaluated from left to right. The final value assigned to a is 15.
Comma as an Operator
The comma operator in C is a binary operator that evaluates multiple expressions from left to right. It discards the result of the preceding expressions and returns the value of the last expression.
- It has the lowest precedence among all C operators.
- It guarantees left-to-right evaluation of expressions and introduces a sequence point between them.
// C Program to Demonstrate
// comma as operator
#include <stdio.h>
int main()
{
int x = 10;
int y = 15;
// using comma as an operator
printf("%d", (x, y));
getchar();
return 0;
}
Output
15
Time Complexity: O(1)
Auxiliary Space: O(1)
Comma as a Separator
A comma as a separator is used to separate multiple variables in declarations and multiple arguments in function calls. It is the most common use of the comma in C and C++.
- Used to separate variables in declarations, such as int a = 1, b = 2;.
- Used to separate function arguments, such as fun(x, y);, without affecting their execution order.
// C Program to Demonstrate
// comma as separator and
// as operator
#include <stdio.h>
int main()
{
// Comma separating x=10 and y
int x = 10, y;
// Comma acting as operator
// y= (x+2) and x=(x+3)
y = (x++, printf("x = %d\n", x), ++x,
printf("x = %d\n", x), x++);
// Note that last expression is evaluated
// but side effect is not updated to y
printf("y = %d\n", y);
printf("x = %d\n", x);
return 0;
}
Output
x = 11 x = 12 y = 12 x = 13
Time Complexity: O(1)
Auxiliary Space: O(1)
Comma Operator in Place of a Semicolon
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.
- The variable declaration statements must be terminated with a semicolon.
- The comma operator can terminate the statements after the declaration statement.
- The last statement of the program must be terminated by a semicolon.
// C Program to illustrate
// the use of comma operator
// in the place of semicolon
#include <stdio.h>
int main(void)
{
printf("First Line\n"),
printf("Second Line\n"),
printf("Third Line\n"),
printf("Last line");
return (0);
}
Output
First Line Second Line Third Line Last line
Time Complexity: O(1)
Auxiliary Space: O(1)