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
?
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 --)
++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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With