Question about operator after increment

Why the following code

int i = 1; 
System.out.print(i += i++);
System.out.print(i);

pin 2 two times instead of 3 for the second pin?

Can anyone shed light on him?

Thank.

+1
source share
5 answers

If you understand that a ++ works as follows (pseudocode):

func ++(ref a)
{
    int b=a;
    a=a+1;
    return b;
}

then it all makes sense.

+4
source

It may seem that in the end I should be 3.

However, if you carefully read the instructions

i += (i++)

equally

i = ( i + (i++) ) 

which in this case is 1 + 1.

A side effect of i ++ is i = i + 1 = 1 + 1 = 2, as you might expect, however, the value i is redefined after assignment.

+3
source

- Java, , , - :

int i = 1;  // iconst_1:    variables { }, stack {1}
            // istore_1:    variables {1}, stack { }
i += i++;   // iload_1:     variables {1}, stack {1}
            // iinc 1, 1:   variables {2}, stack {1}
            // iadd:        variables {2}, stack {2} ...Note that here 1 gets added to the value on stack
            // istore_1:    variables {2}, stack {2} ...Here the variable value will overwrite the stack value

, , .: -)

, , , ...

+2

, , , postfix (expr ++). , , .

int i = 1;
System.out.println(i += i++); // Output: 2

, , :

i++; // i is now 2 for the rest of this statement and the program
i = 1 + 1; // i is assigned again  

, postfix, , i.

, , :

int i = 2;
System.out.println(i += i++); // Output: 4
System.out.println(i); // Output: 4  

:

int i = 2;
System.out.println(i = i + i++ + i--); // Output: 7
System.out.println(i); // Output: 7  

The second line assigns i. The first self is 2, the next self is also 2, but now the third self is 3, because I ++ changed the value of i. As before, i-- will not have any effect on i, because it will be rewritten with i = 2 + 2 + 3.

int i = 1;
System.out.println(i = i++ + i); // Output: 3
System.out.println(i); // Output: 3
+2
source
1 + 1 == 2. 

Hence:

i + i == 2  

and

i += i == 2

and then

i += i++ == 2

Pretty straight forward.

-1
source

All Articles