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++);
}
There is a big difference between postfix and prefix versions of ++
.
In the prefix version (i.e., ++i
), the value of i
is incremented, and the value of the expression is the new value of i
.
In the postfix version (i.e., i++
), the value of i
is incremented, but the value of the expression is the original value of i
.
Let's analyze the following code line by line:
int i = 10; // (1)
int j = ++i; // (2)
int k = i++; // (3)
i
is set to 10
(easy).i
is incremented to 11
.i
is copied into j
. So j
now equals 11
.i
is incremented to 12
.i
(which is 11
) is copied into k
. So k
now equals 11
.So after running the code, i
will be 12 but both j
and k
will be 11.
The same stuff holds for postfix and prefix versions of --
.