Difference between x++ and x+=1? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 7

Difference between x++ and x+=1?

For example: Int x=5; x++ //x=6=>5 x+=1 //???

17th Mar 2018, 1:50 PM
Anastasia Kolesnikova
Anastasia Kolesnikova - avatar
4 Answers
+ 5
In this case there's no difference, because the incremental assignment operator adds 1 to x. However, the post increment operator ++ can only be used to add 1 to the operand, while incremental assignment operator can be used to add any expression or value, e.g x += 5, or x += y * z. Hth, cmiiw
17th Mar 2018, 2:03 PM
Ipang
+ 2
no difference x=5 x+=1 x=6 x++ x=6 as adding or subtracting 1 is very very common, ++ and -- are just shorthand. quick ways to say +=1 The real difference isn't in what they do, but when they do it. notice in this example printing x+=1 results in the new value, while printing y++ simply prints y and then adds the value the second time y is printed it has the new value https://code.sololearn.com/cLEztpIeZ89Q/?ref=app
17th Mar 2018, 1:53 PM
LordHill
LordHill - avatar
+ 1
Eh... The increment operation (x++ or ++x) modifies the variable value and returns itself while x+=1 just returns the value of the expression whilst not modifying it.
17th Mar 2018, 1:59 PM
Robert Fijałkowski
Robert Fijałkowski - avatar
0
To add on, x+=1 is short for x=x+1, so as already mentioned you can use any value in place of 1 but as used by you above the effect is the same. x++ exists because programmers increment variables a lot, & a lot of the time it's by 1. x=x+y also comes up a lot, hence the x+=y shorthand.
17th Mar 2018, 4:45 PM
Jiren The Grey
Jiren The Grey - avatar