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

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.

主站蜘蛛池模板: 磐石市| 昂仁县| 原平市| 济宁市| 高安市| 南康市| 泗水县| 海伦市| 马公市| 高雄市| 新龙县| 新沂市| 普定县| 陆丰市| 庆安县| 枝江市| 金塔县| 偃师市| 壶关县| 建始县| 岢岚县| 黑龙江省| 五指山市| 拜城县| 龙游县| 田林县| 盐源县| 上林县| 白朗县| 青铜峡市| 新干县| 德江县| 龙州县| 常德市| 炉霍县| 甘洛县| 沅江市| 沂源县| 衡南县| 上栗县| 安吉县|