I find the longer version easier to read, but my exams and courses often use +=, -= and /=. Should I switch to the shorthand, or is it fine to keep writing the longer form?
Should I get used to writing i += 1 instead of i = i + 1?
Answers
You don't have to switch, but it's worth getting comfortable reading the shorthand. For a simple numeric variable, i += 1 usually means add one to i and assign the result back to i. Likewise, i -= 2 subtracts two, and i /= 2 divides by two.
Try translating a few expressions into the longer form as you read them. A little practice should make exam questions less distracting, even if you keep using the explicit version in your own code.
Reply to this answer
For your own code, use whichever is clearer to you. In a course or on a team, though, follow any stated style requirements and take cues from the surrounding code. Consistency makes a shared codebase easier to read.
Reply to this answer
One language-specific wrinkle: augmented assignment isn't always identical to spelling out the operation. In Python, for example, += on a list can modify the existing list, while assigning the result of + creates a new list. That difference matters if another variable refers to the same list.
For a simple integer counter, either spelling is generally fine. Just don't assume the two forms behave identically for every type in every language.
Reply to this answer
I wouldn't choose based on speed. For an ordinary numeric increment, the readability and conventions of the code you're working on are better reasons to pick one spelling than a presumed performance difference.
Reply to this answer
Add your answer
Answers are reviewed before publication.
m41+ledgerclip:
For exams, check the instructions rather than assuming either form is required. Reading both comfortably is useful either way.