Why using ++i++ gives an error?

Discussion in 'C' started by raj_ksrt, Mar 3, 2009.

  1. raj_ksrt

    raj_ksrt New Member

    Joined:
    Feb 26, 2009
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    Hi all,

    Why can't use post increment operator along with & or ++ operators ? The compiler complains that it needs an lvalue when i say ++i++ or &i++.


    Please let me know what happens internally with the above two expressions.

    thanks.
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    Because i++ evaluates to a number, not a variable. You can't do ++i++ or &i++ for the same reason you can't do ++5 or &5; neither make sense.
     
  3. raj_ksrt

    raj_ksrt New Member

    Joined:
    Feb 26, 2009
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    But why the following code works?



    Code:
    int main()
    {
    [SIZE=2][COLOR=#0000ff]int[/COLOR][/SIZE][SIZE=2] b=10;[/SIZE]
    [SIZE=2][COLOR=#0000ff]int[/COLOR][/SIZE][SIZE=2] *j=&++b;[/SIZE]
    [SIZE=2]++*j++;[/SIZE]
    [SIZE=2]}[/SIZE]
     
    
     
  4. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    int *j=&++b;
    ++b in value context evaluates to b, which is an lvalue, so its address can be taken.

    ++*j++;
    Preincrement *j and postincrement j. No problem there. Except j will no longer be pointing at a valid object (it points to (&b)+4). You can always preincrement a dereferenced pointer.

    I guess you're misreading ++*j++ as ++(*j)++, since you seem to be comparing it with ++i++. ++*j++ is valid, but ++(*j)++ is not (you get the same error as ++i++), and is a different expression due to operator precedence. ++*j++ is equivalent to ++(*(j++)).
     

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