问题
This is yet another sequence-point question, but a rather simple one:
#include <stdio.h>
void f(int p, int) {
printf("p: %d\n", p);
}
int g(int* p) {
*p = 42;
return 0;
}
int main() {
int p = 0;
f(p, g(&p));
return 0;
}
Is this undefined behaviour? Or does the call to g(&p)
act as a sequence point?
回答1:
No. It doesn't invoke undefined behavior. It is just unspecified, as the order in which the function arguments are evaluated is unspecified in the Standard. So the output could be 0
or 42
depending on the evaluation order decided by your compiler.
回答2:
The behavior of the program is unspecified since we don't know the order of evaluation of the function arguments, from the draft C++ standard 1.9
Program execution paragraph 3:
Certain other aspects and operations of the abstract machine are described in this International Standard as unspecified (for example, order of evaluation of arguments to a function). Where possible, this International Standard defines a set of allowable behaviors. [...]
and all side effects from the arguments are sequenced before the function is entered, from section 5.2.2
Function call paragraph 8:
[ Note: The evaluations of the postfix expression and of the argument expressions are all unsequenced relative to one another. All side effects of argument expression evaluations are sequenced before the function is entered (see 1.9). —end note ]
As for C
both points are covered in the C99 draft standard in section 6.5.2.2
Function calls paragraph 10:
The order of evaluation of the function designator, the actual arguments, and subexpressions within the actual arguments is unspecified, but there is a sequence point before the actual call.
So in both C
and C++
you can end up with either f(0,0)
or f(42,0)
.
来源:https://stackoverflow.com/questions/18516510/sequence-point-from-function-call