Saturday, March 27, 2010

Difference between pre-increment and post-increment

++x is pre-increment and x++ is post-increment that is in the first x is incremented before being used and in the second x is incremented after being used.

Program:
#include
#include

int main(int argc, char **argp)
{
int x = 5;

printf("x=%d\n", ++x);
printf("x=%d\n", x++);
printf("x=%d\n", x);

return EXIT_SUCCESS;
}


output:
x=6
x=6
x=7

Explanation:
In the first printf statement x is incremented before being passed to printf so the value 6 is output, in the second x is passed to printf (so 6 is output) and then incremented and the 3rd printf statement just shows that post increment following the previous statement by outputting x again which now has the value 7.



Q.Why is the pre-increment operator (e.g. ++a) faster than the post-increment operator (e.g. a++)?

Whenever u do post increment, the value of variable is stored in a temporary location ( say any register ) and then the value of that variable is incremented and stored in its mem location.
After incr operation value from register or temp location is stored in whatever it is assigned to
for e;g i=a++, then value of "a" stored in reg will be stored in i.

preincrement doesnot involve the register operation so it is some what faster then post increment.

1 comment:

  1. Dear Madam, i was usefull going through da blog. can u please post examples on pre nd post increment wid are present in aptitude papers. its getting tough to solve those questions.

    ReplyDelete