Comma-Separated Expressions

Discussion in 'C' started by pradeep, May 22, 2006.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    Comma-separated expressions were inherited from C. It's likely that you use such expressions in for- and while-loops rather often. Yet, the language rules in this regard are far from being intuitive. First, let's see what a comma separated expression is.

    An expression may consist of one or more sub-expressions separated by commas. For example:
    Code:
     if(++x, --y, cin.isInt()) /*three expressions*/
    The if condition contains three expressions separated by commas. C++ ensures that each of the expressions is evaluated and its side effects take place. However, the value of an entire comma-separated expression is only the result of the rightmost expression. Therefore, the if condition above evaluates as true only if cin.isInt() returns true. Here's another example of a comma expression:

    Code:
    int j=10;
     int i=0;
     while( ++i, --j)
     {
     /*..repeat as long as j is not 0*/
     }
     
     
  2. Aztec

    Aztec New Member

    Joined:
    May 9, 2006
    Messages:
    90
    Likes Received:
    0
    Trophy Points:
    0
    Nice...Moderator should add this to Tips.
     
  3. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    Added.
     
  4. rahul.mca2001

    rahul.mca2001 New Member

    Joined:
    Feb 13, 2008
    Messages:
    103
    Likes Received:
    0
    Trophy Points:
    0

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice