Basically this is a simple function that writes value to int array.
I want to assign a value to current element, print it and the index out, and self-increasing the index to next element.
However, the changes on order of self-increment makes the results different.
#include <stdio.h>
int buff[5];
int id;
void write ( )
{
int i;
i = id = 0;
printf("Iter 1\n");
while (i++ < 5) {
buff[id] = id;
printf("writes %d in buff[%d]\n", buff[id], id++);
}
i = id = 0;
printf("Iter 2\n");
while (i++ < 5) {
buff[id] = id;
printf("writes %d in buff[%d]\n", buff[id++], id);
}
}
int main ( )
{
write();
}
-------------
Output:
Iter 1
writes 0 in buff[0]
writes 0 in buff[1] // which should not be 0
writes 0 in buff[2] // which should not be 0
writes 0 in buff[3] // which should not be 0
writes 5 in buff[4] // which should not be 5
Iter 2
writes 0 in buff[0]
writes 1 in buff[1]
writes 2 in buff[2]
writes 3 in buff[3]
writes 4 in buff[4]
I know that trying multiple self-increment operation on same variable in an expression may cause problem, but don't know why the self-increment style in Iter 1 here fails to return the correct value of id.
Thanks for any explanation or suggestion.