递增/递减与加法/减法赋值运算符?
免责声明:我是一个相当新的编程人员,所以这个问题可能很愚蠢。
过去,每当我想要增加或减少整数时,我都会使用integer++
或整数--
。然而,在阅读了更多的编程书籍后,我发现了运算符 +=
和 -=
(经过进一步研究,我发现它们被称为加法和减法赋值运算符)。
显然,赋值运算符是最强大的,因为您可以改变要增加或减少整数的数量。我想知道的是:使用integer++
与integer += 1
有什么好处或坏处?
Disclaimer: I'm a rather new programming, so this question might be silly.
In the past, whenever I've wanted to increase or decrease an integer, I would use integer++
or integer--
. However, after reading more programming books, I've discovered the operators +=
and -=
(which upon further research, I discovered are known as the additive and subtractive assignment operators).
Obviously the assignment operators are most robust as you can vary the amount that you want to increase or decrease an integer by. What I'm wondering is: are there are any benefits or disadvantages to using integer++
vs. integer += 1
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
实际上,integer++ 的作用比您想象的要多一些。
整数后的“++”首先返回整数的值,然后递增整数:
您也可以执行 ++integer,它首先递增整数,然后返回值。
至于哪个运营商更好?这取决于个人喜好。 Sven 在评论中指出,这两个函数将输出几乎相同的指令。
(我所说的一切也适用于--)
integer++ actually does a bit more than you might think.
'++' after an integer first returns the value of integer and then increments integer:
You can also do ++integer which first increments the integer and then returns the value.
As to which operator is better? It comes down to personal preference. Sven points out in the comments that both functions will output nearly identical instructions.
(everything I said is also true for --)
++someInteger
和someInteger += 1
完全相同,第一个只是第二个的更短的编写方式。正如 Roy T. 所指出的,如果您在表达式中使用它,则someInteger++
和++someInteger
之间存在差异。但你真的不应该考虑这个,只需使用你觉得更自然的东西即可。这对于性能来说当然不重要。
++someInteger
andsomeInteger += 1
are exactly the same, the first is just a shorter way to write the second. If you use this in an expression there is a difference betweensomeInteger++
and++someInteger
though, as Roy T. pointed out.But you really shouldn’t be thinking about this, just use what feels more natural to you. This certainly doesn’t matter for performance.
另外,只需添加到此线程...您可能还会发现在某些情况下执行 ++integer 而不是 integer++ 很有用(方便)。
请注意,在 for 循环中使用时,integer++ 或 ++integer 没有区别。
Also, just add to this thread... you may also find doing ++integer as opposed to integer++ to be useful (convenient) in some situations.
Note that integer++ or ++integer doesnt make a difference when you use in a for-loop.