i++ Incremements and Execution Sequence


What will the following code print?

int i = 5;
printf("%d ", i++ * i++);
printf("%d\n", i);

One of the first things most C programmers learn “on the job” is that you can’t know when i++ will take place. For example, the following is undefined:

char a[10];
int i=5;
a[i] = ++i;

However, one might think that in the code above, the first i++ will be evaluated as 5, and then the second will start out at 6 (and be increased to 7 after the multipication).

That is not guaranteed. On my PC, gcc returns 25 7 for the code above.

Even more interesting is the following snippet:

int i;
printf("%d %d %d\n", i++, i * i++, i);
printf("%d %d %d\n", i, i * i++, i++);

This prints:

6 25 7
7 36 5


Moral? Don’t be too clever!

Leave a Reply

Your email address will not be published. Required fields are marked *