Comma in C and C++


In C or C++, the comma ‘,’ is used in different purposes. Here we will see how they can be used.

  • Comma as an Operator.

    • The comma operator is a binary operator, that evaluates its first operand, and then discards the result, then evaluates the second operand and returns the value. The comma operator has the lowest precedence in C or C++.

Example

#include<stdio.h>
int main() {
   int x = (50, 60);
   int y = (func1(), func2());
}

Here the 60 will be assigned to x. For the next statement, the func1() will be executed first, then the second one will be executed.

  • Comma as a Separator.

    • During function call or definition, it acts a separator. This is not like comma operator. When comma is used as separator, then all of the items separated by comma will be used, but for operator, it only gets the last one.

Example

#include<stdio.h>
int main() {
   int x = 5, y = 10;
   void function(x, y);
}

Here x and y both will be used as function parameters. The following program will be used to display how the comma operator is used.

Example

#include<stdio.h>
main() {
   int a = 50;
   int b = (a++, ++a);
   printf("%d", b);
}

Output

52

Updated on: 30-Jul-2019

611 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements