开发者

how does pre - increments and post increments work?

开发者 https://www.devze.com 2023-01-08 15:46 出处:网络
Suppose i have initialised two variables like this int a=0; int b=0; Now if i assign b a value like this

Suppose i have initialised two variables like this

int a=0;
int b=0;

Now if i assign b a value like this

b=a++ + ++a + ++a;

Now a=3 and b=开发者_开发百科5 Shouldnt it have been b=2 ? Why is b assigned value 5 ?


lets see:

  • a++ = 0, afterwards increased to 1.

  • ++a = (the one from the a++ plus one preincreased) 2

  • ++a = (the two from the ++a above plus one preincreased) 3

in total: 0 + 2 + 3 = 5

This also explains why a is three. In the last step a is increased to three.


it works like this

b = a++ + ++a + ++a

b = 0 + 2(1+1) + 3(2+1)

b = 5.

and a = 3

In a++ which uses post increment operator, the the current value of the variable is used first and then gets incremented.

but in ++a which uses pre increment operator, the increment happens first and then gets used. so the behavior is as expected.


Let's inspect it with my favorite tool: javap...

The bytecode emitted by Suns javac for

int a = 0;
int b = 0;
b = a++ + ++a + ++a;

looks as follows:

                                             a  b   Stack:
 0: iconst_0      // push 0                  0  0   0
 1: istore_1      // store in a              0  0   empty
 2: iconst_0      // push 0                  0  0   0
 3: istore_2      // store in b              0  0   empty
 4: iload_1       // push value of a         0  0   0
 5: iinc    1, 1  // inc a with 1            1  0   0
 8: iinc    1, 1  // inc a with 1 again      2  0   0
11: iload_1       // push value of a again   2  0   0,2
12: iadd          // add top two elements    2  0   2
13: iinc    1, 1  // inc a with 1            3  0   2  
16: iload_1       // push a again            3  0   2,3
17: iadd          // add top two elements    3  0   5
18: istore_2      // store in b              3  5   empty
0

精彩评论

暂无评论...
验证码 换一张
取 消