What is the difference between prefix and postfix operators?
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 to10
(easy).- Two things on this line:
i
is incremented to11
.- The new value of
i
is copied intoj
. Soj
now equals11
.
- Two things on this line as well:
i
is incremented to12
.- The original value of
i
(which is11
) is copied intok
. Sok
now equals11
.
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 --
.
Prefix:
int a=0;int b=++a; // b=1,a=1
before assignment the value of will be incremented.
Postfix:
int a=0;int b=a++; // a=1,b=0
first assign the value of 'a' to 'b' then increment the value of 'a'
The function returns before i
is incremented because you are using a post-fix operator (++). At any rate, the increment of i
is not global - only to respective function. If you had used a pre-fix operator, it would be 11
and then decremented to 10
.
So you then return i
as 10 and decrement it in the printf function, which shows 9
not 10
as you think.