ans -> x++表示首先使用x的值作为表达式,然后将其增加1
这就是你的情况。RHS上的x的值被复制到LHS上的变量x,然后x的值加1。< / p >
类似地,++x表示->先将x的值加1,然后在表达式中使用
所以在你的例子中,如果你执行x = ++x ; // where x = 7
你会得到8的值。< / p >
为了更清楚,请尝试找出有多少printf语句将执行以下代码
while(i++ <5)
printf("%d" , ++i); // This might clear your concept upto great extend
tmp = x; // ... this is capturing the value of "x++"
x = x + 1; // ... this is the effect of the increment operation in "x++" which
// happens after the value is captured.
x = tmp; // ... this is the effect of assignment operation which is
// (unfortunately) clobbering the incremented value.
// behaves the same as the original code
int x = 7;
int tmp = x; // value of tmp here is 7
x = x + 1; // x temporarily equals 8 (this is the evaluation of ++)
x = tmp; // oops! we overwrote y with 7
这两个赋值都增加x,但不同之处在于when the value is pushed onto the stack的时间
在Case1中,Push发生在增量之前(然后被赋值)(本质上意味着你的增量什么都不做)
在Case2中,Increment首先发生(使其为8),然后压入堆栈(然后分配给x)
案例1:
int x=7;
x=x++;
字节代码:
0 bipush 7 //Push 7 onto stack
2 istore_1 [x] //Pop 7 and store in x
3 iload_1 [x] //Push 7 onto stack
4 iinc 1 1 [x] //Increment x by 1 (x=8)
7 istore_1 [x] //Pop 7 and store in x
8 return //x now has 7
案例2:
int x=7;
x=++x;
字节码
0 bipush 7 //Push 7 onto stack
2 istore_1 [x] //Pop 7 and store in x
3 iinc 1 1 [x] //Increment x by 1 (x=8)
6 iload_1 [x] //Push x onto stack
7 istore_1 [x] //Pop 8 and store in x
8 return //x now has 8