- Expert C++
- Vardan Grigoryan Shunguang Wu
- 186字
- 2021-06-24 16:33:58
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.
推薦閱讀
- Visual Basic程序開發(fā)(學習筆記)
- 兩周自制腳本語言
- DevOps入門與實踐
- 機器人Python青少年編程開發(fā)實例
- QTP自動化測試進階
- Hands-On Swift 5 Microservices Development
- ASP.NET程序設(shè)計教程
- Spring Boot企業(yè)級項目開發(fā)實戰(zhàn)
- HTML5從入門到精通 (第2版)
- PHP從入門到精通(第4版)(軟件開發(fā)視頻大講堂)
- 微服務(wù)從小白到專家:Spring Cloud和Kubernetes實戰(zhàn)
- 持續(xù)輕量級Java EE開發(fā):編寫可測試的代碼
- 一本書講透Java線程:原理與實踐
- 編程可以很簡單
- C編程技巧:117個問題解決方案示例