- 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.
推薦閱讀
- Android 7編程入門經(jīng)典:使用Android Studio 2(第4版)
- Essential Angular
- Building Mobile Applications Using Kendo UI Mobile and ASP.NET Web API
- 精通Python設(shè)計模式(第2版)
- Python數(shù)據(jù)結(jié)構(gòu)與算法(視頻教學(xué)版)
- Advanced Express Web Application Development
- 基于SpringBoot實現(xiàn):Java分布式中間件開發(fā)入門與實戰(zhàn)
- Android移動開發(fā)案例教程:基于Android Studio開發(fā)環(huán)境
- Troubleshooting Citrix XenApp?
- uni-app跨平臺開發(fā)與應(yīng)用從入門到實踐
- Kotlin進(jìn)階實戰(zhàn)
- Visual Basic程序設(shè)計基礎(chǔ)
- C# 7 and .NET Core 2.0 Blueprints
- Building Web and Mobile ArcGIS Server Applications with JavaScript(Second Edition)
- HTML5+CSS3+jQuery Mobile+Bootstrap開發(fā)APP從入門到精通(視頻教學(xué)版)