求值顺序

来源:互联网 发布:微米cms 微信接口 编辑:程序博客网 时间:2024/04/30 20:12

前两天无聊做了几道网上的C++语言题,发现有一些未定义行为被用来出题,觉得真是误人子弟,但同时也确实怪自己基础不扎实,为此特意回炉学习下c++ lauuage

http://en.cppreference.com/w/cpp/language/eval_order

优先级,结合性,求值顺序。

这三个概念咋一看不容易搞清楚,其实他们侧重不同的方面,结合性相对容易理解一点,优先级跟求值顺序则非常容易混淆,引用一段摘自C++标准的原话:

Order of evaluation:Order of evaluation of the operands of any C++ operator, including the order of evaluation of function arguments in a function-call expression, and the order of evaluation of the subexpressions within any expression is unspecified (except where noted below). The compiler will evaluate them in any order, and may choose another order when the same expression is evaluated again.

There is no concept of left-to-right or right-to-left evaluation in C++, which is not to be confused with left-to-right and right-to-left associativity of operators: the expressionf1() + f2() + f3() is parsed as (f1() + f2()) + f3() due to left-to-right associativity of operator+, but the function call tof3 may be evaluated first, last, or between f1() or f2() at run time.

所以很多类似i = ++i + i++;这种最终得到的结果就是undefined behavior,取决于编译器的实现了。

原创粉丝点击