By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,197 Members | 1,173 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,197 IT Pros & Developers. It's quick & easy.

Kindly clarify the ambiguity in the output

P: 48
Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. void main()
  3. {
  4.  
  5.  int f(int);
  6.  int i=f(11);
  7.  printf("\n%d",--i);
  8.  
  9.  
  10.   system("PAUSE");    
  11.   return 0;
  12. }
  13. int f(int i)
  14. {
  15.     return(i++);
  16. }
  17.  
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
Sep 2 '10 #1

✓ answered by rm84

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

Share this Question
Share on Google+
3 Replies


P: 4
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
Sep 2 '10 #2

100+
P: 687
> 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.
Sep 2 '10 #3

P: 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++);
}
Sep 2 '10 #4

Post your reply

Sign in to post your reply or Sign up for a free account.