int b = 1; b = b++; Why is b's final value 1 and not 2? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 6

int b = 1; b = b++; Why is b's final value 1 and not 2?

9th Jan 2017, 2:00 PM
Eligijus Silkartas
Eligijus Silkartas - avatar
8 Answers
+ 7
b = b++ is similar to: var tmp = b; b++; b = tmp; So yeah, b ends up staying as 1 Source: http://stackoverflow.com/a/226019
3rd Feb 2017, 12:48 AM
Jafca
Jafca - avatar
+ 5
yea, but shouldn't b's value be incremented after assignment? Because that's how post increment ++ operator works..
9th Jan 2017, 2:14 PM
Eligijus Silkartas
Eligijus Silkartas - avatar
+ 4
Ok, now that makes sense
3rd Feb 2017, 11:04 AM
Eligijus Silkartas
Eligijus Silkartas - avatar
+ 2
b will assign before it gets incremented. b=b++, means b=1++, first it will assign.
9th Jan 2017, 2:04 PM
Nawaj Shareef
Nawaj Shareef - avatar
0
because if you use b++, b is returned before it gets incremented.
9th Jan 2017, 2:03 PM
Skayo
Skayo - avatar
0
Because if you enter b=b++ the compiler will assign b=b and then it will add 1 with b.. That's why finally it will be 1.. On the other hand if you enter b=++b, then the compiler will add 1 with b first and then it will assign it with b. happy programming :)
26th Jan 2017, 6:29 AM
Sayem Mohammad
Sayem Mohammad - avatar
- 1
b++ es not the same as ++b
10th Jan 2017, 9:52 AM
Alvaro Wenceslao Ponce
Alvaro Wenceslao Ponce - avatar
- 1
if you put "++" the value of b will increase one number
1st Feb 2017, 4:04 PM
Alan Daniel Salas Parada
Alan Daniel Salas Parada - avatar