The following code prints a value of 9. Why? Here return(i++)
will return a value of 11 and due to --i
the value should be 10 itself, can anyone explain how this works?
#include<stdio.h>
main()
{
int i= fun(10);
printf("%d\n",--i);
}
int fun (int i)
{
return(i++);
}
It has to do with the way the post-increment operator works. It returns the value of i and then increments the value.
Actually what happens is when you use postfix i.e. i++, the initial value of i is used for returning rather than the incremented one. After this the value of i is increased by 1. And this happens with any statement that uses i++, i.e. first initial value of i is used in the expression and then it is incremented.
And the exact opposite happens in prefix. If you would have returned ++i, then the incremented value i.e. 11 is returned, which is because adding 1 is performed first and then it is returned.
In fact
return (i++)
will only return 10.The ++ and -- operators can be placed before or after the variable, with different effects. If they are before, then they will be processed and returned and essentially treated just like (i-1) or (i+1), but if you place the ++ or -- after the i, then the return is essentailly
So it will return 10 and never increment it.
The function returns before
i
is incremented because you are using a post-fix operator (++). At any rate, the increment ofi
is not global - only to respective function. If you had used a pre-fix operator, it would be11
and then decremented to10
.So you then return
i
as 10 and decrement it in the printf function, which shows9
not10
as you think.Prefix:
before assignment the value of will be incremented.
Postfix:
first assign the value of 'a' to 'b' then increment the value of 'a'
There is a big difference between postfix and prefix versions of
++
.In the prefix version (i.e.,
++i
), the value ofi
is incremented, and the value of the expression is the new value ofi
.In the postfix version (i.e.,
i++
), the value ofi
is incremented, but the value of the expression is the original value ofi
.Let's analyze the following code line by line:
i
is set to10
(easy).i
is incremented to11
.i
is copied intoj
. Soj
now equals11
.i
is incremented to12
.i
(which is11
) is copied intok
. Sok
now equals11
.So after running the code,
i
will be 12 but bothj
andk
will be 11.The same stuff holds for postfix and prefix versions of
--
.