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 ex
fun(10) returns 10. If you want it to return 11 then you need to use ++i as opposed to i++.
int fun(int i)
{
return ++i;
}
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'
Let's keep this as simple as possible.
let i = 1
console.log('A', i) // 1
console.log('B', ++i) // 2
console.log('C', i++) // 3
console.log('D', i) // 4
A) Prints the value of i B) First i is incremented then the console.log is run with i as it's new value C) Console.log is run with i at its current value, then i will get incemented D) Prints the value of i
In short if you use the pre-shorthand i.e(++i) i will get updated before the line is executed. If you use the post-shorthand i.e(i++) the current line will run as if i had not been updated yet then i gets increased so ther next time your interpreter comes accross i it will have been increrased.
There are two examples illustrates difference
int a , b , c = 0 ;
a = ++c ;
b = c++ ;
printf (" %d %d %d " , a , b , c++);
a = 1
and value of c = 1
next statement assiagn value of c = 1
to b then increment c by 1 so
value of b = 1
and value of c = 2
in printf
statement we have c++
this mean that orginal value of c
which is 2 will printed then increment c by 1 so printf
statement
will print 1 1 2
and value of c now is 3
you can use http://pythontutor.com/c.html
int a , b , c = 0 ;
a = ++c ;
b = c++ ;
printf (" %d %d %d " , a , b , ++c);
printf
statement ++c
will increment value of c by 1 first then
assign new value 3 to c so printf
statement will print 1 1 3
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.
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.