Saturday, November 10, 2012

preincreament and postincreament issue in printf("%d%d%d%d%d",i++,i--,++i,--i,i);

look at this sample code :

void main()
{
      int i=5;
      printf("%d%d%d%d%d", i++, i--, ++i, --i, i);
}

Answer: 45545

Explaination:

The arguments of a function (here printf) are pushed on to the stack from left to right, before evaluation. thus the stack will look like:

top             i
               --i
              ++i
              i--
bottom   i++

Now evaluation will start by poping up each expression from stack and result of expression will be send to its corresponding %d of printf. ie:

> when " i " will be popped its value (ie 5 here in this example)will be send to the 5th %d of printf (since this expression is 5th argument in printf function)

> when " --i " will be popped, since it is predecrement thus decrement to " i " will be done first ie 4 and now send to 4th %d of printf (since this expression is 4th argument in printf function) .

>when " ++i " will be popped , since it is preincrement thus increment to " i " will be done first ie 5 and now send to 3rd %d of printf. (since this expression is 3rd argument in printf function)

>when " i-- "  will be popped , since it is postdecrement thus current value of  " i " ie 5 will be send to 2nd %d of printf (since this expression is 2nd argument in printf function)   and now decrement to " i " will be done ie " i " will be now 4.

>when " i++ "  will be popped , since it is postincrement thus current value of  " i " ie 4 will be send to Ist %d of printf (since this expression is Ist argument in printf function)   and now increment to " i " will be done ie " i " will be now 5(but of no use now since stack is empty).

After stack becomes empty the display task is done by printf ie now the result will be 45545.




1 comment: