+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? */

+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

+5

CarrieForle In C/C++ var = var++; is an undefined behavior, due to sequence point issue. In Java the old value of var is reassigned to var due to postfix operation.

+3

Because it will first assign the value then increment it...that's why v is 5

+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

+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 !

+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

+1

Because this is post increment 🤗

+1

I think you should go with var = var++, as in this case you are sending old value,