Explain comma operator with an example in C-programming language

0
19

In C programming language, comma (,) works as a separator and an operator too and its behavior is little different according to the place where it is used.

comma (,) as seperator: While declaration multiple variables and providing multiple arguments in a function, comma works as a separator.

Example of the comma (,) as a separator:

int x,y,z;

In this statement, the comma is a separator and tells the compiler that these (x, y, and z) are three different variables.

comma (,) as operator: Sometimes we assign multiple values to a variable using a comma, in that case, a comma is known as an operator.

Example of the comma (,) as an operator:

x = 100,200,300;
y = (100,200,300);

In the first statement, the value of x will be 100, because the assignment operator (=) has more priority more than a comma (,), thus 100 will be assigned to the variable x.
In the second statement, the value of y will be 300, because 100, 200, 300 are enclosed in braces, and braces have more priority than assignment (=) operator. When multiple values are given with comma operator within the braces, then the rightmost value is considered as a result of the expression. Thus, 300 will be assigned to the variable y.
Example of a comma (,) as an operator and as a separator:

#include <stdio.h>

int main()
{
	int x,y;
	x = 100,200,300;
	y = (100,200,300);
	//printing the values
	printf("x= %d, y= %d\n",x,y);
	return 0;
}
Output:

x= 100, y= 300
This program may confuse you, read the program carefully and predict the output...

#include <stdio.h>

int main()
{
	int a= 100,200,300;
	int b;
	
	b= (100,200,300);

	//printing the values
	printf("a= %d, b= %d\n",a,b);
	return 0;
}
Output:

Compile-time error

prog.c: In function 'main':
prog.c:5:12: error: expected identifier or '(' before numeric constant
  int a= 10,20,30;
            ^

Explanation: Consider the statement: int a= 10,20,30; It is a declaration with initialization statement and here comma is a separator and we cannot use values like this.

LEAVE A REPLY

Please enter your comment!
Please enter your name here