I have a small C code:
#include<stdio.h> int main() { int z[]= {1,2,3,4,5,6}; int i = 2, j; printf("i=%d \n",i); z[i] = i++; for (j=0;j < 6;j++ ) printf ("%d ", z[j]); printf("\ni=%d \n",i); }
output:
i=2 1 2 2 4 5 6 i=3
Priority order for evaluating an expression First, z [i] is evaluated. Since I am here 2, it becomes z [2]. Then I ++ evaluates to ie 2, and I becomes 3. Finally, = is executed, and 2 (ie, the value obtained from i ++) is placed in z [2]
This explains the above conclusion ie 1 2 2 4 5 6
But if we change the above code from i ++ to ++ i i.e.
#include<stdio.h> int main() { int z[]= {1,2,3,4,5,6}; int i = 2, j; printf("i=%d \n",i); z[i] = ++i; for (j=0;j < 6;j++ ) printf ("%d ", z[j]); printf("\ni=%d \n",i); }
Then the conclusion is strangely different, namely:
i=2 1 2 3 3 5 6 i=3
if we go to the above priority (that C spec says that [index] are linked earlier than ++), then the output should have been 1 2 3 4 5 6.
I just want to know why this priority order doesn't explain this?
my compiler is gcc 4.5.2 on ubuntu 11.04
Thanks and Regards, Kapil