官术网_书友最值得收藏!

The switch statement

Conditionals such as the switch statement use the same logic as shown:

switch (age) {
case 18:
can_drink = false;
can_code = true;
break;
case 21:
can_drink = true;
can_code = true;
break;
default:
can_drink = false;
}

Let's suppose rax represents the age, rbx represents can_drink, and rdx represents  can_code. The preceding example will translate into the following assembly instructions (simplified to express the basic idea):

cmp rax, 18
je CASE_18
cmp rax, 21
je CASE_21
je CASE_DEFAULT
CASE_18:
mov rbx, 0; cannot drink
mov rdx, 1; can code
jmp BEYOND_SWITCH; break
CASE_21:
mov rbx, 1
mov rdx, 1
jmp BEYOND_SWITCH
CASE_DEFAULT:
mov rbx, 0
BEYOND_SWITCH:
; ....

Each break statement translates into jumping to the BEYOND_SWITCH label, so if we forget the break keyword, for example, in the case where age is 18, the execution will reach through  CASE_21 as well. That's why you should not forget the break statement.

Let's find a way to avoid using conditionals in the source, both to make the code shorter and possibly faster. We will use function pointers.

主站蜘蛛池模板: 南川市| 宜阳县| 瑞丽市| 临颍县| 日喀则市| 山阴县| 合山市| 虞城县| 唐河县| 山东省| 廊坊市| 将乐县| 东至县| 新乡市| 肇源县| 锡林浩特市| 合川市| 理塘县| 社旗县| 饶河县| 清徐县| 军事| 和田县| 黄石市| 汤原县| 永嘉县| 深水埗区| 拉孜县| 宣恩县| 乌鲁木齐县| 南江县| 金寨县| 利川市| 海晏县| 东阳市| 庆城县| 射阳县| 商水县| 噶尔县| 乳源| 秀山|