测试代码
/// @file 2015_1026\exam_1_2\main.c
/// @brief
/**
switch-case分析
*/
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main(int argc, char** argv)
{
int iCase = 0;
srand(time(NULL));
iCase = (int)(255 * rand() / RAND_MAX);
switch (iCase)
{
case 1:
printf("iCase = %d\n", iCase);
break;
case 4:
printf("iCase = %d\n", iCase);
break;
case 7:
printf("iCase = %d\n", iCase);
break;
case 10:
printf("iCase = %d\n", iCase);
break;
default:
printf("iCase = %d\n", iCase);
break;
}
getchar();
return 0;
}
运行效果
分析
17:
18: switch (iCase)
19: {
00401058 mov edx,dword ptr [ebp-4]
0040105B mov dword ptr [ebp-8],edx
0040105E mov eax,dword ptr [ebp-8]
00401061 sub eax,1
00401064 mov dword ptr [ebp-8],eax
00401067 cmp dword ptr [ebp-8],9
0040106B ja $L1160+13h (004010cb)
0040106D mov edx,dword ptr [ebp-8]
00401070 xor ecx,ecx
00401072 mov cl,byte ptr (0040114d)[edx]
00401078 jmp dword ptr [ecx*4+401139h]
401139h 为switch跳转表首地址
ecx 为 caseN, caseN是作过优化的N从0开始到4结束
在memory窗口查看 switch跳转表首地址401139h
每个地址是4个字节,按照long Hex显示
在vsIDE中打开反汇编,可以看到每个case的地址
case1 地址 0040107F
case4 地址 00401092
case7 地址 004010A5
case10 地址 004010B8
default 地址 004010CB
可以看到每个case的地址在switch跳转表中依次排列