Why is `index = index ++` increment `index` not being indexed?

** Dup: What's the difference between X = X ++; vs X ++ ;? **

So, while I know you never do this in code, I'm still wondering:

public static void main(String[] args) {
    int index = 0;
    System.out.println(index);   // 0
    index++;
    System.out.println(index);   // 1
    index = index++;
    System.out.println(index);   // 1
    System.out.println(index++); // 1
    System.out.println(index);   // 2
}

      

Note that the third sysout

is still 1

. In my opinion, the string index = index++;

means "set the index to be indexed and then increment the index by 1" in the same way System.out.println(index++);

means "pass the index to the println method and then increase the index by 1".

However, it is not. Can anyone explain what is going on?

0


source to share


8 answers


This is a duplicate question.

EDIT: I can't find the original: P oh well

a = a ++ uses post-increment, which your compiler interprets as:



a = function() {
   var old_value = a;
   a++;
   return old_value;
}

      

EDIT 2: What is the difference between X = X ++; vs X ++ ;?

+4


source


value++;

is an increment of posts.

int firtValue = 9;
int secondValue = firstValue++;

      

firstValue is now 10, but secondValue is 9, the value of firstValue before it was incremented.



Now pre-incremented:

int firtValue = 9;
int secondValue = ++firstValue;

      

firstValue and secondValue are now 10, fistValue is incremented and then its value is assigned to secondValue.

+3


source


The assignment occurs after the expression has been evaluated. Therefore index ++ is 0, although as the side effects index increases. Then the value (0) is assigned to the index.

+1


source


The post-increment operator increments index++

this variable, but returns its old value, thus

int i = 5;
System.out.println(i++);

      

will print 5, but now i am equal to 6.

if you want to return value after increment operation use ++index

+1


source


I've never tried anything like this, but I'm willing to be that the assignment happens after the increment.

So what really happens with regard to the compiler:

  • Index score
  • Save the index value for later
  • Increase index value
  • Assign the old index value, thereby destroying the increment.
+1


source


You have to see what things are being evaluated.

in the following statement

index = index ++;

Three things happen 1) since this is the c ++ index, the value of the index is determined 2) the index is incremented, 3) the value that was determined in the first step is then assigned to the variable on the left side of the equation

0


source


The answer to this question should help. The post increment updates the index value, but returns the value before the update.

-1


source


-1


source







All Articles