This blog is under construction

Monday, 30 December 2013

Comma operator in C

Basically, comma operator is used to separate expressions.  Consider the following,

i++, j++, k++, val = val + 10;

Here, there are four expression and they are separated by comma operator.  The above statement is equivalent to the following.

i++;
j++;
k++;
val = val + 10;

Comma operator is most often used in for statement and function arguments.  Below are few examples on comma operator usage.

Example 1: (comma operator in for loop)
for (i = 0, j = 0, k = 0; i < 10; i++, j++, k++) {
      : :
}

Example 2: (comma operator in function argument)
int add(int a, int b) {  // comma operator
      return (a + b);
}

main() {
       add(10, 20);  // comma operator in function argument
}


Example C program using comma operator

  #include <stdio.h>
  void add(int a, int b) {
        printf("Sum of %d and %d is %d\n", a, b, a + b);
  }

  int main() {
        int i, j, k, val = 0;  // variable declaration

        /* comma operator in for loop */
        for (i =0, j = 0, k = 0; i < 5; i++, j++, k++) {
                printf("Hello world\n");
        }

        /* comma operator in function argument */
        printf("\ni = %d, j = %d, k = %d\n", i, j, k);
        i++, j++, k++, val = val + 10; // comma operator in statement
        printf("i = %d, j = %d, k = %d, val = %d\n", i, j, k, val);
        add(10, 20);  // comma operator in function argument
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Hello world
  Hello world
  Hello world
  Hello world
  Hello world

  i = 5, j = 5, k = 5
  i = 6, j = 6, k = 6, val = 10
  Sum of 10 and 20 is 30



No comments:

Post a Comment