Ha! I have an explanation (for the gcc compiler). But it seems to fit!!
Note: I am copying my own answer from a fb group. So, I am using the following code snippet as reference:
int i=10;
printf("%d,%d,%d,%d",i++,++i,i++,++i);
Pre-increment operators work like, they first update, and then, we get to use the value. Post-increment does it like, we get to use the value first and then update.
Again, on a stack-based function evaluation model, the operands get ‘evaluated’ right-to-left. So, the first expression that we get is ++i. That increments the value of i to 11. But since, this is a pre-increment, we won’t use the value, until the whole bunch of things get evaluated. So, we need to put in the value of i as the 4th argument, which will happen at the very end.
Then, we have an i++, so, we use the value we have in hand, which is 11. Hence the value 11 as the third one. We, of course do update i to 12.
Then, we have a ++i again, so we just increment the value of i to 13.
Then, we have an i++, and we use the value 13, to get the first number as 13. The remaining update takes i to 14.
Now, since everything that can be done has been done, we need to plug in the values of i wherever they were required (due to the pre-increment). So, we have two 14s, at the second and fourth place.
That gives us the answer 13, 14, 11, 14
.
In fact, the same argument holds up for these following as well.
int i = 10;
printf("%d, %d, %d, %d\n", i++, ++i, ++i, i++);
printf("%d, %d, %d, %d\n", --i, i--, i--, --i);
will give you
13, 14, 14, 10
10, 12, 13, 10
I hope, this clears your doubts.
But, this explanation only fits for the gcc compiler. For other compilers. the answer might vary and will need another explanation.
So, the expected answer for such problems will vary from compiler to compiler. But, the above one seems to fit for gcc compiler.
Now, you can easily see, why
int i=5;
printf("%d %d %d ",++i,++i,++i);
gives the answer as 8 8 8
.