I am trying to understand the difference between index = index--; and index=--index; I checked the output of index = index--; assignment in the below code block (first example):
public static void main(String[] args) {
int index = 10;
for (int i = 0; i < 10; i++) {
index = index--;
System.out.println("Index:" + index);
}//end of for loop
}// end of main method
Output:
Index:10
Index:10
Index:10
Index:10
Index:10
Index:10
Index:10
Index:10
Index:10
Index:10
When I use the index=--index; assignment (second example)
public static void main(String[] args) {
int index = 10;
for (int i = 0; i < 10; i++) {
index = --index;
System.out.println("Index:" + index);
}
}// end of main method
Output:
Index:9
Index:8
Index:7
Index:6
Index:5
Index:4
Index:3
Index:2
Index:1
Index:0
I have two questions. In the second example Eclipse throws a warning: assignment index = --index;(The assignment to variable index has no effect) But actually it does have an effect on the variable. It decreases its value by 1. Why does Eclipse gives such a warning message?
In the first example, the variable is not affected by the operation (and Eclipse gives no warning). I wonder why Eclipse has no message, and I don’t understand why this assignment has no effect over the variable index index = index--;
Both
=and--alter the value ofindex. In the case of Java, the--is guaranteed to happen before the=, so in the case ofindex = index--;the return value of--is the old value ofindexand overwrites the decrement ofindexwhile in the case ofindex = --index;the return value of--is already the new value ofindexso the assignment has no effect andindexstays decremented.Note that in C the statement
index = index--;has undefined behaviour and compilers are allowed to decrement index, ignore it or write code that reformats your hard disk (although the latter case is extremely unlikely).