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 trialkingedwards
5,977 PointsIs there a reason to use i+= 1 and not I++?
.
1 Answer
Steven Parker
231,248 PointsAssuming your language supports both operations, one reason the first one might be preferred is simply for readability, since the increment amount is part of the expression. Another reason might be flexibility, as you can change the increment amount simply by changing the digit.
But a potentially more important reason for the choice would be if these expressions are used as part of larger expressions or statements, they have different values. The addition assignment operation ("i+=1
") has the value of the final assignment, but the post-increment operation ("i++
") has the value of the variable before the increment is performed. For example:
a = b = 6; // start with a and b both 6
x = (a += 1);
y = b++;
// at this point, a and b are both 7, and x is also 7 but y is 6
Jason Anello
Courses Plus Student 94,610 PointsJason Anello
Courses Plus Student 94,610 PointsHi Edwards,
What lesson is this for?
Or at least what language is this for and I can change the category from "general discussion" to something more relevant.