Computer >> Computer tutorials >  >> Programming >> C programming

A comma operator question in C/C++ ?


Comma Operator in C/C++ programming language has two contexts −

  • As a Separator −

  • As an operator − The comma operator { , } is a binary operator that discards the first expression (after evaluation) and then use the value of the second expression. This operator has the least precedence.

Consider the following codes and guess the output −

Example

#include <stdio.h>
int main(void) {
   char ch = 'a', 'b', 'c';
   printf("%c", ch);
   return 0;
}

Output

It gives an error because the works as a separator.

prog.c: In function ‘main’:
prog.c:5:20: error: expected identifier or ‘(’ before 'b'
char ch = 'a', 'b', 'c';
^~~

Example

#include <stdio.h>
int main(void) {
   char ch;
   ch = 'a','b','c';
   printf("%c", ch);
   return 0;
}

Output

It gives a as output as it works because the ‘,’ works as operator but it precedence is below assignment operator hence the output is a.

a

Example

#include <stdio.h>
int f1() {
   return 43;
}
int f2() {
   return 123 ;
}
int main(void) {
   int a;
   a = (f1() , f2());
   printf("%d", a);
   return 0;
}

Output

It gives 123 as output as the ‘, ’ works as operator and being in braces it works and evaluates the second expression and gives output.

123