i++
i++ 如果有表达式运算,是先参与表达式计算,然后再自加1。具体见代码说明:
int a = 2;
int b = a++;
System.out.println("Test " + a + " " + b);
输出结果:
a = 3;b = 2
---------------
int a = 2;
a = a++;
System.out.println("Test " + a);
输出结果:
a = 2
--------------
int a = 2;
a++;
System.out.println("Test " + a);
输出结果:
a = 3
++i
++i 如果有表达式运算,是先自行加1,然后用自加后的值参与运算。具体见代码说明:
int a = 2;
int b = ++a;
System.out.println("Test " + a + " " + b);
输出结果:
a = 3;b = 3
---------------
int a = 2;
a = ++a;
System.out.println("Test " + a);
输出结果:
a = 3
--------------
int a = 2;
++a;
System.out.println("Test " + a);
输出结果:
a = 3
复合运算( i++ + ++i)
int a = 2;
int b = a++ + ++a;
System.out.println("Test " + a + " " + b);
输出结果:
a = 4;b = 6
解析说明:
- a++ 时,a = 2,
有表达式,先运算,再自加1
所以,b = 2,a = 3 - ++a 时,a = 3,
有表达式,先自行加1,再用自加后的值参与运算
所以此时 a = 4,b = 4 - 最后b = 2 + 4 = 6
- 按上面的计算,那 a 不该是 5 或 7 吗。其实仔细看,
a 并没有经过表达式运算赋值
只是经历了 i++ 和 ++i ,所以 a 也只是经过了两次自行加1
所以 a = 2 + 1 + 1 = 4
一些栗子
int a = 0;
int b = 0;
for (int i = 0; i < 99; i++) {
a = a++;
}
System.out.println("Test " + a + " " + b);
for (int i = 0; i < 99; i++) {
a = ++a;
}
System.out.println("Test " + a + " " + b);
a = 0;
b = 0;
for (int i = 0; i < 99; i++) {
b = a++;
}
System.out.println("Test " + a + " " + b);
a = 0;
b = 0;
for (int i = 0; i < 99; i++) {
b = ++a;
}
System.out.println("Test " + a + " " + b);
输出结果:
Test 0 0
Test 99 0
Test 99 98
Test 99 99