pre post increament?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vishalgoswami
    New Member
    • Nov 2012
    • 1

    pre post increament?

    Code:
    #include<stdlib.h>
    #include<stdio.h>
    int main()
    {
    int i=5;
    printf("%d\n",i);
    printf("%d\n",i++);
    printf("%d\n",++i);
    printf("%d - %d - %d\n",i,i++,++i);
    }
    /*how output is like that?
    5
    5
    7
    9 - 8 - 9
    */
    Last edited by Meetee; Nov 8 '12, 11:37 AM. Reason: please add code tags <code/> around your code
  • Meetee
    Recognized Expert Contributor
    • Dec 2006
    • 928

    #2
    It is because

    printf("%d\n",i ); 5, as it is apparent
    printf("%d\n",i ++); 5, as it will first print and then increment. After this line execution, i = 6
    printf("%d\n",+ +i); 7, as first increment and make it 7 and then print
    printf("%d - %d - %d\n",i,i++,++i ); 9 - 8 - 9, I am not very sure, but compiler executes this in reverse order.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      Code:
      printf("%d - %d - %d\n",i,i++,++i); 9 - 8 - 9, I am not very sure, but compiler
      This code will produce indeterminate results. While the comma operator executes the actions in order, there is no provision in the standard as to when the variable will be changed. It just has to be changed before leaving the statement. Therefore, the value in the variable is indeterminate when the change is applied.

      Do not modify the same variable more than once in the same statement.
      Last edited by weaknessforcats; Nov 9 '12, 02:44 PM. Reason: typo

      Comment

      • Shubhangi24
        New Member
        • Oct 2012
        • 20

        #4
        It is mostly environment dependant. If you will do the same program on TC(Turbo C) it will give you the answer as:
        /*
        5
        5
        7
        9 - 8 - 8
        */

        Comment

        Working...