Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialNicholas Chan
1,281 PointsWhat is the difference between i+=1 and i++
I found out that i++ is an increment of i by whereas in this chapter, the teacher uses i+=1 instead. May I know what is the difference between two? Thank you very much.
4 Answers
Laura Cressman
12,548 PointsThere is no difference, both do the same thing.
The i++
is shorthand for i += 1
.
You can use other numbers for +=, like "i += 2" if you wanted to print only even numbers, for example, but i++
only increments by one. We also have i--
, which is the same as i -= 1
.
Does that make sense?
Russell Beye
3,367 PointsLet's explore this side-by-side:
i++: Here, the value of i is returned first, then it is incremented. In a common example, if you set i = 1, and x = i++, you should find that x = 1. This is called post increment.
++i: In this case, i is first incremented and then returned. Again, i = 1, x = ++i, you'll find x = 2. This is called pre increment.
In an overwhelming amount of cases, this won't be a problem as it won't affect your loops. It's nice to know what is out there though. I would prefer to use i++ because it maintains the form of a proper expression; the target operand is on the left side of the expression.
You can learn more: http://stackoverflow.com/questions/24853/what-is-the-difference-between-i-and-i
Nicholas Chan
1,281 PointsThanks Laura for the answer!
Russell Beye
3,367 PointsDon't forget that we also have ++i, which can have different side effects than i++. ;)
Nicholas Chan
1,281 PointsHi Russell, can you tell me more about ++1? Like what does this formula returns?