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



2 comments:

  1. Hello Everyone !

    USA SSN Leads/Dead Fullz available, along with Driving License/ID Number with good connectivity.

    All SSN's are Tested & Verified.

    **DETAILS IN LEADS/FULLZ**

    ->FULL NAME
    ->SSN
    ->DATE OF BIRTH
    ->DRIVING LICENSE NUMBER
    ->ADDRESS WITH ZIP
    ->PHONE NUMBER, EMAIL
    ->EMPLOYEE DETAILS

    *Price for SSN lead $2
    *You can ask for sample before any deal
    *If you buy in bulk, will give you discount
    *Sampling is just for serious buyers

    ->Hope for the long term business
    ->You can buy for your specific states too

    **Contact 24/7**

    Whatsapp > +923172721122

    Email > leads.sellers1212@gmail.com

    Telegram > @leadsupplier

    ICQ > 752822040

    ReplyDelete
  2. Dell Laptop Service center are giving repair service at the door. We should high quality Dell out of warranty Laptop Repair, removal of virus, screen removal, wireless network set up, battery removal, motherboard replacement to several other are offered at budget friendly price and it’s Negotiable. We can fix them all in time by our well experience and certified technicians. If you want to repair your laptop in front of your eyesight, than you may call us: 7217871051

    ReplyDelete