Expression evaluation in C++ involving unary operators [duplicate]

依然范特西╮ 提交于 2020-01-07 08:07:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!