increment

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Nandadulal
    New Member
    • Jun 2010
    • 8

    increment

    sir,
    would u plz .explain me that in c language if I take a value
    int p=1;
    {
    print("%d,%d",+ +p,p++);
    }
    the output should be 2,1 because first preincrement so , we get 2, then for p we get 1. but it shows different result why?
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Changing the value of a variable more than once in a statement produces undefined results.

    The reason is that the order of evaluation is irrelvant. In your case you have ++p and p++.

    The ++p is a prefix increment. The compiler is free to increment anytime before the end of the statement. Therefore, when you get to p++ you have either 1 (the compiler is waiting) or 2 (the compiler is not waiting).

    Worse, the arguments can be evaluated in any order. Maybe it goes right to left. Now its p++ first which is 2
    and then ++p which is now 3.

    In short, when you use a variable more than once in the same statement (called a sequence point), any rule you make up to explain the result is bogus.

    Comment

    Working...