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对应 指令的高级实现进而为性能优化提供选择。而其它多数高级语言不会给你选择的权利。

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

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.

原文链接: https://www.cnblogs.com/thinkingfor/p/3171788.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/94541

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月10日 上午2:40
下一篇 2023年2月10日 上午2:40

相关推荐