Comma Operator

This is a discussion on Comma Operator within the C Programming forums, part of the General Programming Boards category; The sample code below uses comma operator, Code: #include <stdio.h> int inc(int i) { return ++i; } int main(int argc, ...

  1. #1
    Registered User
    Join Date
    Dec 2003
    Posts
    24

    Comma Operator

    The sample code below uses comma operator,

    Code:
    #include <stdio.h>
    
    int inc(int i)
    {    
       return ++i;    
    }
    
    int main(int argc, char **argv)
    {
       int a,b,c;
       a = b = c = 0;
       while( ++a, a=inc(a), a < 3) 
       {
          while( b=1, c=inc(c), c < 3)
              ++b, b=inc(b), ++b;
       }
       printf("%d %d %d\n", a,b,c);
    }

    I don't understand the condition(s) in the while-loop,
    all the 3 conditions are to be satisfied (or) it is totally one condition
    - If it is one condition then what is the return value of the condition? i.e., which statement's return value is it?.
    - If it is 3 conditions then is ',' similar to '&&' ??

    ( ++a, a=inc(a), a<3 )

    Please somebody tell me in short, How to use ',' operator?

  2. #2
    Registered User
    Join Date
    Mar 2003
    Posts
    143
    The comma operator seperates two expressions which are
    evaluated left to right. The result of the right expression is
    returned as the value of the whole thing. So, taking the
    example from K&R:
    Code:
      f(a, (t=3, t+2), c);
    The second argument passed to the function uses a comma
    operator (the parentheses are needed) and the value is 5.

    in your example:
    Code:
      while( b=1, c=inc(c), c < 3)
        ++b, b=inc(b), ++b;
    
      /* is equivalent to */
    
      b=1;
      c=inc(c);
      while(c < 3) {
        ++b;
        b=inc(b);
        ++b;
    
        b=1;      /* makes the rest of the loop rather pointless! */
        c=inc(c);
      }
    HTH
    Last edited by DavT; 12-09-2003 at 05:23 AM.
    DavT
    -----------------------------------------------

  3. #3
    Registered User
    Join Date
    Dec 2003
    Posts
    24
    great explanation!!!!

    Thanx a lot.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Smart pointer class
    By Elysia in forum C++ Programming
    Replies: 63
    Last Post: 11-03-2007, 08:05 AM
  2. C comma operator problem
    By greenberet in forum C Programming
    Replies: 10
    Last Post: 07-22-2007, 03:47 AM
  3. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 03:39 PM
  4. Operator Overloading (Bug, or error in code?)
    By QuietWhistler in forum C++ Programming
    Replies: 2
    Last Post: 01-25-2006, 08:38 AM
  5. operator overloading and dynamic memory program
    By jlmac2001 in forum C++ Programming
    Replies: 3
    Last Post: 04-07-2003, 12:51 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21