问题
UPDATE: As marked by user ecatmur, it's a duplicate of In C99, is f()+g() undefined or merely unspecified? (although the questions asks about C99, but answer is unchanged for C++). And the answer is: unspecified (for both cases).
Consider following C++14 code fragment:
int i = 0;
int x() { i++; return i;}
int y() { i++; return i;}
bool z = (x() > y()); // unspecified or undefined ?
Is the value of z
merely unspecified, or is this undefined behavior ?
As per my understanding (please correct if I am wrong), an expression of the kind: i++ > i++
will be undefined behavior, as we are mutating same variable twice between a pair of sequence points, but what about the case above (where mutation happen in separate functions) ?
And what about this one:
bool z = (x() > i++); // undefined or unspecified now ?
回答1:
In both cases, the value is unspecified, but behaviour is well-defined. Function calls are indeterminately sequenced with respect to other evaluations in the expression that calls them, as specified in [intro.exececution] 1.9/15:
Every evaluation in the calling function (including other function calls) that is not otherwise specifically sequenced before or after the execution of the body of the called function is indeterminately sequenced with respect to the execution of the called function
So all accesses to i
are sequenced, giving well-defined behaviour, but the sequence is indeterminate, giving an unspecified value.
回答2:
It is unspecified behavior.
Reference: http://en.cppreference.com/w/cpp/language/eval_order :
The order of evaluation of the subexpressions within any expression is unspecified
Both bool z = (x() > y());
and bool z = (x() > i++);
are unspecified behavior.
The only assumption you can do is x()
and y()
will be processed before >
.
There is no guarantee for anything else.
来源:https://stackoverflow.com/questions/28816936/is-the-value-of-expression-f-g-when-f-g-modify-same-global-variable-und