Explain comma operator with an example in C language

Comma (,) as Separator and Operator: In this article, we are going to learn how and where comma (,) is used in a c programming language?

In this article, I am going to explain about the comma sign in C language. In C programming language, comma (,) works as a separator and an operator too and its behaviour is little different according to the place where it is used.

1) Comma (,) as separator

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

Example:

int a,b,c;

In this statement, comma is a separator and tells to the compiler that these (a, b, and c) are three different variables.

2) Comma (,) as an operator

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

Example:

a = 10,20,30;
b = (10,20,30);

In the first statement, value of a will be 10, because assignment operator (=) has more priority more than comma (,), thus 10 will be assigned to the variable a.

In the second statement, value of b will be 30, because 10, 20, 30 are enclosed in braces, and braces has more priority than assignment (=) operator. When multiple values are given with comma operator within the braces, then right most value is considered as result of the expression. Thus, 30 will be assigned to the variable b.

Consider the program:

#include <stdio.h>

int main()
{
	int a,b;
	a = 10,20,30;
	b = (10,20,30);
	//printing the values
	printf("a= %d, b= %d\n",a,b);
	return 0;
}

Output

a= 10, b= 30

This program may confuse you, read the program carefully and predict the output...

#include <stdio.h>

int main()
{
	int a= 10,20,30;
	int b;
	
	b= (10,20,30);

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

If you are thinking that output would be a= 10, b= 30 then you are wrong!

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.

This will be correct output (which is a compile time error):

main.cpp: In function ‘int main()’:
main.cpp:5:12: error: expected unqualified-id before numeric constant
  int a= 10,20,30;
            ^~



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.