java k++ 和C/C++ k++的区别
import java.io.*;
public class D
{
static public void main(String[] args)
{
int k=0;
for(int i=0;i<200;i++){
k = k++;
}
System.out.println(k);
}
}
结果 k = 0;
#include <stdio.h>
int main(void)
{
int k=0;
for(int i=0;i<200;i++)
{
k=k++;
}
printf("%d",k);
return 0;
}
结果k=200;
java字节码分析代码如下:
Compiled from "D.java"
public class D extends java.lang.Object{
public D();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_0
1: istore_1
2: iconst_0
3: istore_2
4: iload_2
5: sipush 200
8: if_icmpge 22 // 比较跳转
11: iload_1 // 载入k的值
12: iinc 1, 1 // k+1
15: istore_1 // 回填k的值, k的值先被保存起来了,执行了操作后,k的值再被回填回去,实际上k的值没有变
16: iinc 2, 1 // i+1
19: goto 4
22: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
25: iload_1
26: invokevirtual #3; //Method java/io/PrintStream.println:(I)V
29: return
}
C++ 汇编分析如下:
1: // Test111.cpp : Defines the entry point for the console application.
2: //
3:
4: #include "stdafx.h"
5: #include <stdio.h>
6:
7: int main(int argc, char* argv[])
8: {
00401010 push ebp
00401011 mov ebp,esp
00401013 sub esp,48h
00401016 push ebx
00401017 push esi
00401018 push edi
00401019 lea edi,[ebp-48h]
0040101C mov ecx,12h
00401021 mov eax,0CCCCCCCCh
00401026 rep stos dword ptr [edi]
9: int k=0;
00401028 mov dword ptr [ebp-4],0
10: for (int i=0;i<200;i++)
0040102F mov dword ptr [ebp-8],0
00401036 jmp main+31h (00401041)
00401038 mov eax,dword ptr [ebp-8]
0040103B add eax,1
0040103E mov dword ptr [ebp-8],eax
00401041 cmp dword ptr [ebp-8],0C8h
00401048 jge main+4Bh (0040105b)
11: {
12: k=k++;
0040104A mov ecx,dword ptr [ebp-4] // k的值进ecx
0040104D mov dword ptr [ebp-4],ecx // 执行k=k
00401050 mov edx,dword ptr [ebp-4] // k的值再进ecx
00401053 add edx,1 // 寄存器中的值+1
00401056 mov dword ptr [ebp-4],edx // 寄存器+1后的值存入k,实际上k+1了。
13: }
00401059 jmp main+28h (00401038)
14: printf("%d",k);
0040105B mov eax,dword ptr [ebp-4]
0040105E push eax
0040105F push offset string "%d" (0042201c)
00401064 call printf (004010a0)
00401069 add esp,8
15: return 0;
0040106C xor eax,eax
16: }
大家自己分析吧。