Kindly clarify the ambiguity in the output

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vensriram
    New Member
    • Aug 2010
    • 48

    #1

    Kindly clarify the ambiguity in the output

    Code:
    #include <stdio.h>
    void main()
    {
        
     int f(int);
     int i=f(11);
     printf("\n%d",--i);
    
    
      system("PAUSE");	
      return 0;
    }
    int f(int i)
    {
        return(i++);
    }
    For the above code my compiler prints the output as 10. I expected the output as 11. But the increment is not taking place. Hence kindly clarify the case. Thanks in advance
  • rm84
    New Member
    • Sep 2010
    • 4

    #2
    return(i++);

    Postfix : Returns the value 11 and then increments i to 12.

    int i=f(11);

    The returned value gets assigned to i (11 in this case) which over writes the incremented value (12).

    printf("\n%d",--i);

    Prefix : Decrements the value of i by 1 an then prints it (11-1 = 10)

    If u need the answer to be 11, use this

    return(++i);

    instead of

    return(i++);

    ---
    Robin

    Comment

    • newb16
      Contributor
      • Jul 2008
      • 687

      #3
      > The returned value gets assigned to i (11 in this case) which over writes the incremented value (12).

      It does not overwrite anything, because the incremented i was local to function f() and increment never modified 'i' of main. Even if the return value were discarded or assigned to other variable, ( e..g j = f(i) ), i in main would not be modified by the increment.

      Comment

      • rm84
        New Member
        • Sep 2010
        • 4

        #4
        Thanks for pointing that out, my bad for overlooking the fundamental concept of variable scope.
        another way of getting the desired result would be this (note the use of post increment in the return statement):

        int i;
        int f(int);

        int main (void)
        {
        int j=f(11);
        cout<<"The retuned value from the fucntion is: "<<j<<endl;
        cout<<"The final decremented value of global variable 'i' is:"<<--i<<endl;
        return 0;
        }

        int f(int k)
        {
        i=k;
        return (i++);
        }

        Comment

        Working...