mikeage.net Logo
mikeage.net/2006/10/07/i-incremements-and-execution-sequence/

mikeage.net @ י׳ מנחם אב תשע״ח

i++ Incremements and Execution Sequence

Quiz:

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;
i=5;
printf("%d %d %d\n", i++, i * i++, i);
i=5;
printf("%d %d %d\n", i, i * i++, i++);

This prints:

6 25 7
7 36 5

Yikes.

Moral? Don't be too clever!

Leave a Reply

Quick Map
Content +
Personal +
Archives +
Site Stuff +
RBS Weather +
Search +
Recent Images

Valid XHTML 1.1!
Printer Friendly Page
 

Last Modified: September 04, 2006 @ 02:11 CST

Memory(TRUE): 4194304/4194304
Memory(FALSE): 2986640/2996624