Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment / decrement vs. additive / subtractive assignment operators?

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?

like image 773
Kevin Yap Avatar asked May 07 '11 06:05

Kevin Yap


2 Answers

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

like image 155
Roy T. Avatar answered Nov 15 '22 23:11

Roy T.


++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.

like image 23
Sven Avatar answered Nov 16 '22 00:11

Sven