问题
Is the following undefined or implementation-defined:
int x = 0;
printf("%d%d", ++x, x);
The order of evaluating arguments is unspecified, so:
- if
++x
is evaluated first, this prints11
. - if
x
is evaluated first, it prints10
.
回答1:
printf("%d%d", ++x, x);
This is clearly undefined behavior in C++.
(C++11, 1.9p15) "If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined."
Same for C (emphasis mine):
(C99, 6.5.p2) "Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression.72) Furthermore, the prior value shall be read only to determine the value to be stored.73"
Note that C11 has now a similar wording as in C++11:
(C11, 6.5p2) "If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined."
来源:https://stackoverflow.com/questions/11657100/is-this-undefined-behavior-or-implementation-defined