i++,++i,i+=1,i = i+1在C++中的區別

其實這個問題能夠從三個角度去分析:語言規範,編譯器實現,CPU支持。首先從語言規範上來說;前置++和後置++是不等價的,前置++在規範中明確指出 和+=組合操做符是等價的,但和E = E+1;這樣的賦值操做不等價,由於後者對操做數E須要進行兩次求值,而+=組合操做符只進行一次求值。後置++表示操做數做爲結果值被獲取以後操做數的 原值再進行更新。 聰明的編譯器能夠根據應用場景進行優化(標準不規定相關優化的手段,由編譯器自決),但不能過分依賴這種優化,由於編譯器仍是不如人聰明,並且複雜的表達式也不必定能夠優化掉。從 CPU的角度上來說CPU支持什麼樣的指令集是絕對決定了相應操做符計算效率。在嵌入式開發中不一樣的CPU之間的差別就大了。好比說PowerPC CPU就沒有直接能夠對應後綴++的t自增指令,某些版本的ARM CPU沒有任何自增指令(不管是前置仍是後置式的)。所以不管從CPU支持來說仍是編譯器優化來看前置++確定是高效的,後置++的即時CPU和編譯器優化都支持也不能比前置++更高效,在使用的時候應該儘可能使用前置++。C/C++提供這麼多操做符是由於它是最接近底層的高級語言,它須要儘量實現CPU對應 指令的高級實現進而爲性能優化提供選擇。而其它多數高級語言不會給你選擇的權利。express

下面是標準中的相關信息:性能優化

The value of the operand of the prefix ++ operator is incremented. The result is the new
value of the operand after incrementation. The expression ++E is equivalent to (E+=1).
See the discussions of additive operators and compound assignment for information on
constraints, types, side effects, and conversions and the effects of operations on pointers.

The result of the postfix ++ operator is the value of the operand. After the result is
obtained, the value of the operand is incremented. (That is, the value 1 of the appropriate
type is added to it.) See the discussions of additive operators and compound assignment
for information on constraints, types, and conversions and the effects of operations on
pointers. The side effect of updating the stored


A compound assignment of the form E1 op= E2 differs from the simple assignment
expression E1 = E1 op (E2) only in that the lvalue E1 is evaluated only once.app

相關文章
相關標籤/搜索