Reputation: 1007
I recently wrote snippet code like this
public class TestIncrement {
public static void main(String[] args){
double a = 12.4;
double b = 5.6;
a -=b -=b -= b -= b -= b -= b;
System.out.println(a);
a-=b;
System.out.println(a);
}
}
and the output is:
12.4
12.4
Why increment operator not work?
Upvotes: 0
Views: 175
Reputation: 8960
You could have figured this out on your own, by writing a simpler example.
public static void main(String[] args){
int a = 1;
int b = 2;
int c = 3;
a -= b -= c;
System.out.println(a + " " + b + " " + c);
}
You'd be surprised to see that the output is 2 -1 3
This reason is, the above code is equal to:
public static void main(String[] args){
int a = 1;
int b = 2;
int c = 3;
b -= c;
a -= b;
System.out.println(a + " " + b + " " + c);
}
Don't do spaghetti code. :(
Upvotes: 0
Reputation: 16987
If I put parentheses around all that to make it easier to understand, we get this:
public class TestIncrement {
public static void main(String[] args){
double a = 12.4;
double b = 5.6;
a -= (b -= (b -= (b -= (b -= (b -= b)))));
System.out.println(a);
a -= b;
System.out.println(a);
}
}
The first b -= b
statement sets b
to 0
. After 0
is subtracted from b
4 more times, the result is still 0
, which obviously leaves the value of a
unchanged. Even if you try again, in the a -= b
line, you will still get the same result: 12.4 − 0.0 = 12.4
.
Upvotes: 1
Reputation: 280181
-=
and all other assignment operators are right-associative. This line:
a -=b -=b -= b -= b -= b -= b;
doesn't mean "decrease a
by the value of b
6 times". It means the same as this:
a -= (b -= (b -= (b -= (b -= (b -= b)))));
which means "decrease b
by the value of b
, then decrease b
by the new value of b
, then do that 3 more times, then decrease a
by the final value of b
". b
is 0 after the first -=
, so the rest of the statement does nothing, as does the
a-=b;
line.
Upvotes: 9
Reputation: 14276
It does work. Your b
variable is equal to 0.
Upvotes: 2