Jun 16, 2014

C Programming #14: Operators - Comma

This article deals with comma operator used in C. Comma operator evaluates from left to right and returns right most value.

e.g following expression -

a, b, c, d, e

Is evaluated as in order of a b c d e and returns e.

Note that all use of comma is as operator it is used as separator also. Best usage of it, multiple variable declaration can be combined using comma operator

int a;
int b;
int c;

Can be combined as
int a, b, c;
If there is initialization to be done, it can be done as
int a = 10, b, c = 20;

Program depicting usage of comma as operator.

#include <stdio.h>
int main()
   int a, b;
   a = 1, 2, 3;
   b = (1, 2, 3);

   printf("Value of a is %d\n", a);
   printf("Value of b is %d\n", b);

   return 0;

Output of the above program is

Value of a is 1
Value of b is 3

In the statement a = 1, 2, 3 there are two operators one is assignment and another is comma. In C assignment has higher precedence when compared to comma. Next section Precedence of operator deals with such item only. Hence a is assigned value 1 then the comma operator is evaluated which returns 3 which is not assigned to anything.
a = 1 is treated as one entity by C. While in the second statement we are putting () making sure comma is evaluated first and then the assignment is evaluated.


Quiz - Not Yet written !!
Next Article - C Programming #15: Operators - Expression and Statement
Previous Article -  C Programming #13: Operators - Increment, Decrement
All Article - C Programming

No comments :

Post a Comment