i have 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
The order of precedence to evaluate the expression is First, z[i] is evaluated. As i is 2 here, it becomes z[2]. Next, i++ is evaluated i.e 2 is yielded and i becomes 3. Finally, = is executed, and 2 (i.e value yielded from i++) is put to z[2]
This explains the above output i.e 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 Output is strangely different, which is:
i=2
1 2 3 3 5 6
i=3
if we go by the above precedence (what C spec says [index] are bound earlier than ++) then the output should have been 1 2 3 4 5 6.
I just wish to know that why the above order of precedence does not explains this ?
my compiler is gcc 4.5.2 on ubuntu 11.04
Thanks and Regards, Kapil