r/javahelp • u/VanVleet-goes-for-22 Nooblet Brewer • May 29 '20
Solved Can Someone explain why x = x++; doesn’t change the value of x?
This is probably a common ask but it’s been bugging me. I was told that x++ would use its original value in the assignment, then increment to x+1 afterwards.
Let’s say
y = 2 + x++;//x was 3.
y now equals 5 and x equals 4 right?
Why doesn’t x = 2 + x++; work the same? Is it because Java knows that trying to define the same variable as 2 different things on the same line is confusing?
Edit: I understand it now, thanks so much for your help!!
14
u/sucmadik May 29 '20
The x++ is an expression which means it returns a value. Now in the case of x++, the incrementation happens but it's the original value of x that is returned. Contrarily to the ++x in which the incrmentation happens but the new value is returned.
4
u/mjg123 May 29 '20 edited May 29 '20
In an assignment, the RHS is evaluated then the LHS variable is assigned that value.
If x=2, the line x = x++; goes as follows:
the RHS of
x++evaluates to 2 (and in evaluating it sets the value of x to 3).Then the value of x is set to 2 (replacing the 3 which was made in the previous step)
Edit: RHS/LHS is "right-hand side" and "left-hand side", in case that wasn't clear.
3
u/SSOMGDSJD May 29 '20
Y = 2 + X++ says y is equal to the sum of 2 and x, then increase x by one.if you want x to be increased then added to 2 use
Y = 2 + ++x
3
u/TheCrazyPhoenix416 May 29 '20
x++ is an operator. It does the same thing as:
int increment(int& x) {
int tmp = x;
x = x + 1;
return tmp;
}As you can see, it increments it, but returns the value before incrementing.
Then if you set x back to x++, you're incrementing x, then setting x back to it's prior value.
It would be the same as the following code:
// x++
int tmp = x;
x = x + 1;
// x = x++
x = tmp2
1
-4
u/Mordan May 29 '20 edited May 29 '20
the question is moot.
This kind of code is banned in my code base.
Anyone using this crap without explaining things in a comment is fired.
Java is about readability. One line. One statement.
x++ was completely removed in Swift.. For good reasons.
3
u/VanVleet-goes-for-22 Nooblet Brewer May 29 '20
I agree that this will never be used outside of theory but I’m studying for the OCA and this was one of the questions.
0
May 30 '20
[deleted]
2
u/VanVleet-goes-for-22 Nooblet Brewer May 30 '20
I agree that “my way” of doing is stupid, but it wasn’t my choice lol. I’m studying for the OCA exam and this was a question. The book told me x = x++; would give me x but for me, just taking someone’s word for it won’t help me in the long run, so I wanted to get a better fundamental understanding behind why
12
u/rickkyaa May 29 '20
I think it is because you define x value on line X = 2 + x++; // x is 3.
When x++ is is executed the x value becomes 4, however it’s value is overriden by the sum of 2 + x++ (2 + 3) and in this way x value is 5.
Hope it this helped.