Why doesn't var = var++ increase? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

Why doesn't var = var++ increase?

something like this: int var = 5; var = var++; cout << var; (System.out.println(var);) /*The output is 5 on Java and C++. Shouldn't the variable increase after 2nd line? */

24th Aug 2019, 2:21 AM
你知道規則,我也是
你知道規則,我也是 - avatar
7 Answers
+ 15
We've had quite some discussion on x = x++ before in the Q&A. The reason is because you are assigning the old value of var back to var after incrementing it with postfix, i.e. The postfix increment happens before the assignment. https://www.sololearn.com/discuss/1271878/?ref=app
24th Aug 2019, 2:35 AM
Hatsy Rei
Hatsy Rei - avatar
+ 3
Because this is post increment 🤗
25th Aug 2019, 2:11 AM
Sanjay Kamath
Sanjay Kamath - avatar
+ 3
Because it will first assign the value then increment it...that's why v is 5
25th Aug 2019, 12:58 PM
Riya sachan
Riya sachan - avatar
+ 1
Shouldnt you use x = ++x instead? Idk about c++ and java but if they have the same rule on "++" as c# then x = x++ simply takes the x first and then add by 1, but it doesnt get added cuz the variable x already took its own value. While ++x add by 1 then assign the variable. Pls correct me if im wrong, im new at this
24th Aug 2019, 10:47 PM
Ahmad Faris Khawarizmi
Ahmad Faris Khawarizmi - avatar
+ 1
because it will first assign value of var then it will increment it, as it is assignment operation the right hand side value is only for operation, it will not change and the value of that operation is assigned to variable at left hand side. a=3; b=3; c=a+b; here value of a+b is assigned to c but value of a and b is same as before.. hope you get it !
24th Aug 2019, 11:30 PM
Nabil Malik
Nabil Malik - avatar
+ 1
In c++ you must write ++var for the pre incrementation and var++ for the post incrementation Write var+=value( var = var+ value) So for var++ is same as var+=1
25th Aug 2019, 12:48 AM
cleevens luxama
+ 1
I think you should go with var = var++, as in this case you are sending old value,
25th Aug 2019, 5:35 AM
Yatin Verma
Yatin Verma - avatar