问题
Why does not C/C++ evaluates expression in order of left to right in these cases: Initially x=1
Evaluating x + ++x gives 4.
If normal evaluation is carried out (precedence of ++ is higher than +) then the result should be 1 + 2 = 3
Similarly:
x + ++x + x gives 6
x + x + ++x gives 4
Why are results different?
More Cases:
x + x++ +x gives 5
What rule is followed by C/C++ instead?
回答1:
Specifically the results of these expressions are not defined, this is because of Cs requirement for multiple accesses (excluding cases where all accesses are reads) to always have a sequence point between them (such as a ; or ,). The results you are getting there are effectively random and would depend on your compiler or theoretically could even change between runs of your program, please see here for information on sequence points:
http://en.wikipedia.org/wiki/Sequence_point
And here if you want to learn about undefined behavior (what your misuse of the variable causes):
http://en.wikipedia.org/wiki/Undefined_behavior#Examples_in_C_and_C.2B.2B
来源:https://stackoverflow.com/questions/21878364/expression-evaluation-in-c-involving-unary-operators