} } }

    i++,++i,i+=1,i = i+1在C++中的差别

    添加时间:2013-7-4 点击量:

    其实这个题目可以从三个角度去解析:说话规范,编译器实现,CPU支撑。起首从说话规范上来讲;前置++和后置++是不等价的,前置++在规范中明白指出 和+=组合操纵符是等价的,但和E = E+1;如许的赋值操纵不等价,因为后者对操纵数E须要进行两次求值,而+=组合操纵符只进行一次求值。后置++默示操纵数作为成果值被获取之后操纵数的 原值再进行更新。 聪慧的编译器可以按照顾用处景进行优化(标准不规定相干优化的手段,由编译器自决),但不克不及过度依附这种优化,因为编译器还是不如人聪慧,并且错杂的表达式也不必然可以优化掉。从 CPU的角度上来讲CPU支撑什么样的指令集是绝对决意了响应操纵符策画效力。在嵌入式开辟中不合的CPU之间的差别就大了。比如说PowerPC CPU就没有直接可以对应后缀++的t自增指令,某些版本的ARM CPU没有任何自增指令(无论是前置还是后置式的)。是以无论从CPU支撑来讲还是编译器优化来看前置++必然是高效的,后置++的即时CPU和编译器优化都支撑也不克不及比前置++更高效,在应用的时辰应当尽量应用前置++。C/C++供给这么多操纵符是因为它是最接近底层的高等说话,它须要尽可能实现CPU对应 指令的高等实现进而为机能优化供给选择。而其它多半高等说话不会给你选择的权力。


    下面是标准中的相干信息:


    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 the simple assignment
    expression E1 = E1 op (E2) only in that the lvalue E1 is evaluated only once.

    容易发怒的意思就是: 别人做了蠢事, 然后我们代替他们, 表现出笨蛋的样子。—— 蔡康永
    分享到: