can someone provide me more insight on why this code works the way it works
#include <stdio.h>
int main()
{
int a[5] = {1,2,3,4,5};
int i;
for(i=0;i<5;i++)
{
printf("%d,%d \n",i[a],i[a]++);
}
return 0;
}
开发者_如何学编程The result is
2,1
3,2
4,3
5,4
6,5
Thanks
The behavior is undefined.
N1256 6.5p2:
Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.
The program both modifies i[a]
(in i[a]++
) and reads its value (in the next argument), and the result of reading the value is not used to determine the value to be stored.
This is not just a matter of the unspecified order of evaluation of function arguments; the fact that there's no sequence point between i[a]++
and i[a]
(since that's not a comma operator) means that the behavior, not just the result, is undefined.
It works by undefined behaviour. The order of evaluation of function arguments is not defined. The comma is not a sequence point.
EDIT: ooops, I read to fast. There is only one write to the a[i] object, so the behaviour is not undefined, only the results.
"i[a]++" is a post increment, so it will return the value of i[a] and then increment i[a] right away.
In your case, the third parameter of printf gets evaluated before the second (the evaluation order of function parameters is unspecified as far as I know), and thus the second parameter returns the already incremented value.
精彩评论