in C this works as I expect
void foo(int a, int b ) { printf("%i,%i ",a,b ); }
int main()
{
int i=1;
foo(i++,i);
foo(i++,i);
foo(i++,i);
foo(i++,i);
return(0);
}
output: 1,2 2,3 3,4 4,5
Now, the following does not work as I would have guessed: void foo(int a, int b ) { printf("%i,%i ",a,b ); }
int main()
{
int a[] = { 100,200,300,400,500,600,700 };
int i=0;
foo(a[i++],a[i]);
foo(a[i++],a[i]);
foo(a[i++],a[i]);
foo(a[i++],a[i]);
return(0);
}
It returns 100,100 200,200 300,300 400,400
Following the logic of the previous example, I would have expected 100,200 200,300 300,400 400,500
My first suspicion was that the increment was only called after the function call, however, as the first example shows, i is indeed incremented inside the function call, unless it is used as an index for the array.
I also tried the same using foo(*(a+(sizeof(int)i++)),(a+(sizeof(int)*i))); just to check, and it also acts like the second example.
The compiler is gcc version 4.6.3
My question is, why does it work when I'm using the variable i directly as the function parameter, but not when I use the variable i as an index for an array which is used as the function parameter?