switch相比if else的实现,其优势是执行效率不会因为分支的增加而变慢。
这个是如何实现的嗯,一切的奥秘就在于有个跳转表。
注意,gcc编译switch时使用跳转表需要分支在4个以上(具体多少个看gcc的实现)
-
int switchtest(int a, int b, int c)
-
{
-
int ret;
-
switch(a){
-
case 1:
-
ret = b+c;
-
break;
-
case 2:
-
ret = b+2*c;
-
break;
-
case 3:
-
ret = b+3*c;
-
break;
-
case 4:
-
case 5:
-
ret = b+5*c;
-
}
-
return ret;
-
}
arm-linux-gcc -O2 switch.c -S
-
switchtest:
-
@ Function supports interworking.
-
@ args = 0, pretend = 0, frame = 0
-
@ frame_needed = 0, uses_anonymous_args = 0
-
@ link register save eliminated.
-
sub r0, r0, #1 @a-1 ,存入r0
-
cmp r0, #4 @把r0和4比较
-
ldrls pc, [pc, r0, asl #2] @pc+r0*4,然后执行PC指向的命令,设计非常精巧
-
b .L2
-
.L7:
-
.word .L9
-
.word .L4
-
.word .L5
-
.word .L6
-
.word .L6
-
.L6:
-
add r2, r2, r2, asl #2 @r2里面存的是5c,下面会继续执行.L9,即b+5c,这里被优化了
-
.L9:
-
add r3, r2, r1 @b+c
-
.L2:
-
mov r0, r3
-
bx lr
-
.L5:
-
add r2, r2, r2, asl #1 @r2 = r2*2
-
add r3, r2, r1 @r3 = r1+r2, 就是b+3c的意思
-
mov r0, r3
-
bx lr
-
.L4:
-
add r3, r1, r2, asl #1 @b+2c
-
mov r0, r3
-
bx lr
阅读(2477) | 评论(0) | 转发(0) |