Why is i++ and ++i same in the following code?
#include <stdio.h>
int main()
{
int i=5;
while(1)
{
i++; /*replacing i++ by ++i also gives 6*/
printf("%d",i);
break;
}
return 0;
}
The output is 6. I learnt that the increment operator i++ has its value the current value of i and causes the stored value of i to be incremented.But i's value is displayed as 6 though the current value of i is 5. Replacing i++ by ++i also gives the same value 6. Why is i++ and ++i same in this case and why output is 6 though initial value is 5.
The order of execution is sequential.
i++ or for that matter ++i is a single instruction to be executed at that sequence point, with i's value not being used anywhere at that instruction, so it doesn't really matter.
If you do replace printf("%d",i); with printf("%d",i++); or printf("%d",++i); things will be much different.
EDIT: I also discovered something that is fairly useful to know. In C and C++, the prefix unary operator returns an lvalue, in contrast to the postfix unary operator, so if you want to, for example, decrement i twice, then
(i--)--; // is illegal
whereas
(--i)--; // is perfectly legal and works as intended.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With