++nc vs nc = nc + 1
在 K&R 第 1 章中:
语句
++nc
提供了一个新的运算符++
,这意味着加一。您可以改为编写nc = nc + 1
,但++nc
更简洁,而且通常更高效。
什么时候预增量比替代方案更有效?至少对于大多数事情来说,两者的汇编都是 add
(编辑:或 inc
)指令。它们什么时候有区别?
In K&R Ch 1:
The statement
++nc
presents a new operator,++
, which means increment by one. You could instead writenc = nc + 1
, but++nc
is more concise and often more efficient.
When would pre-increment be more efficient than the alternative? For most things, at least, the assembly for both is the add
(edit: or inc
) instruction. When do they differ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
该文本早已过时。在 70 年代,编译器可能会为 ++n 生成更有效的输出,但现在情况并非如此。所有现代编译器都会生成相同的代码。
That text is long out dated. It might have been true in the 70's that compilers would produce more efficient output for ++n, but not any more. All modern compilers will produce identical code.
这并不完全正确:通常有一个 单独的“递增一”指令。然而,这是无关紧要的,因为任何半体面的编译器都会为
++nc
和nc = nc + 1
生成相同的机器代码。换句话说,没有性能差异。当这本书写的时候,编译器不是很好,可能曾经有过这种情况,但现在已经不存在了。
That's not quite true: there is often a separate "increment by one" instruction. However, that's irrelevant since any half-decent compiler will produce identical machine code for
++nc
andnc = nc + 1
.In other words, there is no performance difference. There may have been when the book was written and compilers were not very good, but there isn't anymore.
我不确定,我只是大声思考(也许我不应该):也许在 K&R 的时代,
++nc
被编译成比更高效的东西nc = nc + 1(例如,增量指令,而不是加法)。然而如今,编译器可能会自动优化这一点。
I don't know for sure, I'm just thinking out aloud (maybe I shouldn't): Perhaps in K&R's time,
++nc
was compiled into something more efficient thannc = nc + 1
(e.g., an increment instruction, rather than an addition). Nowadays, however, compilers probably optimise this automagically.这是我用
gcc -S
看到的。我会让你得到你想要的!下面是
1.c
的.s
文件的内容,与2.s和3.s相比,指令是相同的!This is what I could see with
gcc -S <filename>
. I'll let you derive what you want!The below is the content of the
.s
file for1.c
and the instructions are identical when compared with 2.s and 3.s!对于“正常”变量,应该没有其他答案所暗示的差异。仅当
nc
被voloatile
限定时,结果可能会有所不同。对于这样的变量,+1
形式必须首先计算表达式nc
,即加载nc
,然后执行添加。对于++
形式,编译器仍然可以采用快捷方式并就地增加变量。For "normal" variables there should be no difference as other answers suggest. Only if
nc
isvoloatile
qualified the result could be different. For such a variable the+1
form must first evaluate the expressionnc
that is loadnc
and then perform the addition. For the++
form the compiler still could take shortcuts and increment the variable in place.