递增/递减与加法/减法赋值运算符?

发布于 2024-11-05 07:40:05 字数 331 浏览 0 评论 0原文

免责声明:我是一个相当新的编程人员,所以这个问题可能很愚蠢。

过去,每当我想要增加或减少整数时,我都会使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

心是晴朗的。 2024-11-12 07:40:05

实际上,integer++ 的作用比您想象的要多一些。

整数后的“++”首先返回整数的值,然后递增整数:

int i = 5;
int a = i++; 
//a is now 5
//i is now 6.
i++;
//i iw now 7

您也可以执行 ++integer,它首先递增整数,然后返回值。

int i = 5;
int a = ++i;
//i and a are now 6.

至于哪个运营商更好?这取决于个人喜好。 Sven 在评论中指出,这两个函数将输出几乎相同的指令。

(我所说的一切也适用于--)

integer++ actually does a bit more than you might think.

'++' after an integer first returns the value of integer and then increments integer:

int i = 5;
int a = i++; 
//a is now 5
//i is now 6.
i++;
//i iw now 7

You can also do ++integer which first increments the integer and then returns the value.

int i = 5;
int a = ++i;
//i and a are now 6.

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 --)

当梦初醒 2024-11-12 07:40:05

++someIntegersomeInteger += 1 完全相同,第一个只是第二个的更短的编写方式。正如 Roy T. 所指出的,如果您在表达式中使用它,则 someInteger++++someInteger 之间存在差异。

但你真的不应该考虑这个,只需使用你觉得更自然的东西即可。这对于性能来说当然不重要。

++someInteger and someInteger += 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 between someInteger++ 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.

玩物 2024-11-12 07:40:05

另外,只需添加到此线程...您可能还会发现在某些情况下执行 ++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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文