Comma Operator in C programming Language | Comma operator in depth analysis with examples
Comma ( , ) token in C :
- The Comma ( , ) is used as Operator and Separator in C programming language.
- Comma act as separator in variables declarations, function calls, function definitions.
- Comma operator is binary operator, Means it works on two operands
- Comma operator separates the Expressions. the separated expressions are evaluated from Left to right.
Comma As Separator :
int a=1, b=2, c=3, d=4;
Here Comma act as separator.
Comma As Operator :
program 1: Understanding Comma Operator in C programming Language :
-
#include<stdio.h>
-
int main()
-
{
-
int a=1, b=2, c ; // here comma is Separator
-
c = a , b ; // here comma is Operator
-
printf(“a = %d b = %d c = %d”,a,b,c);
-
return 0;
-
}
a = 1 b = 2 c = 1
In Above program statement c = a , b ; contains comma operator, Initially a value is assigned to c. so c value become 1 and then b is discarded.
lets take a other scenario of above program with small modification
Program 2 : Understanding the Behavior of Comma operator in C programming Language
-
#include<stdio.h>
-
int main()
-
{
-
int a=1, b=2, c ; // here comma is Separator
-
c = ( a , b ); // here comma is Operator
-
printf(“a = %d b = %d c = %d”,a,b,c);
-
return 0;
-
}
output :
a = 1 b = 2 c = 2
See the output of second program c contains 2 that means value of b.because of the parenthesis around a and b.(please look carefully second program contains parenthesis in line no 5).
c = ( a , b) ;
If multiple expressions are separated by Comma in a group (group means covered by parenthesis), then all the expressions are evaluated from left to right and group value is the Right most expression value.
So above expression is group of expressions so rightmost expression value is assigned to c.
Related Posts :
- Compilation Stage/ phases in programming
- Arithmetic Operators with Examples.
- Arithmetic operators priority and it’s Associativity.
- Modulus Operator and Hidden Concepts of Modulus Operator.
- Precedence Table or Operators Priority Table.
- Assignment Operator, Usage, Examples
- Increment Operator and Different types of Increment operators Usage with Examples.
- Decrement Operator and Different types of Decrement operators with Examples.
3 Responses
[…] Comma Operator. […]
[…] Comma Operator. […]
[…] The assignment operator has the Lowest Precedence or Priority compared to all other operators except Comma Operator. […]