Thread: C doubt

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2013
    Posts
    1
    Rep Power
    0

    C doubt


    int x,i=10;
    x=++i + ++i + i++;
    x=36
    but not 35 why
  2. #2
  3. Lord of the Dance
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Oct 2003
    Posts
    3,582
    Rep Power
    1906
    Do you know the difference between ++i (prefix) and i++ (postfix)?
    If not, I suggest you look it up.

    You can also try to split the line, e.g. that happens first, second etc.
  4. #3
  5. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,145
    Rep Power
    2222
    Yet another perennial crop of homework dealing with horrible examples of code that you must never write. <<sigh>>

    Read up on sequence points (that's a link to a Wikipedia article).

    Then read my explanation of a similar futile exercise, Evaluating (x + x * ++x).

    Bottom line: if you really want to know why an expression was evaluated the way that it was, then read the assembly code that the compiler generated.

    HINT: an expression like that can be handled differently by different compilers, so you cannot predict what answer you'll get. You'll have to read the assembly code generated by each compiler to figure it out.
    Last edited by dwise1_aol; April 4th, 2013 at 09:11 AM.
  6. #4
  7. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,379
    Rep Power
    1871
    My same (broken code), many compilers, and many DIFFERENT answers test

    Read it.

    Better yet, show it to your teacher, and maybe they'll stop asking stupid questions about undefined behaviour in the mistaken belief that they're teaching you some useful deep C magic.

    They're not - the code is out and out rubbish.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper

IMN logo majestic logo threadwatch logo seochat tools logo