int main(){
int a[3]={1,10,20};
int *p=a;
printf("%d %d " ,*++p,*p);
return 0;
}
The output to the code above is 10 1 on a g开发者_如何学Gocc compiler.
I understand that *++p increments p and dereferences the new value. But since p has been incremented, why does *p return 1 instead of 10?
It's unspecified behaviour in what order function argument expressions are evaluated. Some compilers might use left-to-right, some right-to-left, and some might do a different evaluation order depending on the situation for optimalization. So in your case *p
gets evaluated before *++p
which results in your "weird output".
The comma between *++p
and *p
does not denote a sequence point, so this is undefined unspecified behavior. The compiler is free to
evaluate *p
before *++p
.
Undefined behaviour, output may various on different compiler.
Apparently, your arguments are being evaluated in reverse order (last to first) so *p
is evaluated first and it will return 1
.
As others have pointed out, the standard does not dictate what order the arguments are evaluated and so this behavior may or may not look the same with other compilers.
精彩评论