C++26,Switch語句
大家好,我是梁唐。
這是EasyC++系列的第26篇,咱們來聊聊switch語句。
想要追求更好閱讀體驗的同學(xué),可以點擊文末的「閱讀原文」,訪問github倉庫。
switch
在日常的開發(fā)當(dāng)中,我們經(jīng)常會遇到一種情況,我們用一個變量表示狀態(tài)。比如關(guān)閉-激活-完成,當(dāng)我們需要判斷狀態(tài)的時候,就需要羅列if-else語句。
- if (status == 'closed') {
- // todo
- }else if (status == 'activated') {
- // todo
- }else if (status == 'done') {
- // todo
- }
如果只有少數(shù)幾個還好,當(dāng)我們要枚舉的狀態(tài)多了之后,寫if-else就會非常繁瑣。所以C++當(dāng)中提供了switch語句來代替簡單的if-else的羅列。
- switch(expression) {
- case constant1:
- //todo
- case constant2:
- //todo
- case constant3:
- //todo
- default:
- //todo
- }
要注意的是,switch語句當(dāng)中的expression只能是一個整數(shù)或者是枚舉類型,不能是其他類型。比如像是string就不可以作為switch語句的case,這個非???,很容易不小心寫錯。
所以上面的if-else語句可以改寫成:
- switch (status) {
- case 1:
- // todo1
- break;
- case 2:
- // todo2
- break;
- case 3:
- // todo3
- break;
- default:
- //todo
- }
最后的default表示默認(rèn)情況,也就是當(dāng)之前的所有可能都不滿足時會執(zhí)行defalut標(biāo)簽下的內(nèi)容。還有一點需要注意,switch語句有點像是路牌,它只是根據(jù)expression的值將代碼跳轉(zhuǎn)到對應(yīng)的位置,并不是只運行對應(yīng)標(biāo)簽的代碼。
比如當(dāng)我們的status為1時,代碼會跳轉(zhuǎn)到todo1處,在執(zhí)行完todo1之后依然會繼續(xù)往下執(zhí)行todo2、todo3的代碼。如果我們只希望執(zhí)行todo1的代碼,需要在末尾加上break,表示執(zhí)行結(jié)束,跳出。這也是一個坑點,加不加break完全是兩種效果。
數(shù)字1、2、3表示狀態(tài)顯然會導(dǎo)致含義不夠明顯,所以我們也可以使用枚舉類型:
- enum status {closed, done, activated};
- status st;
- switch (st) {
- case closed:
- //todo
- break;
- case done:
- //todo
- break;
- case activated:
- //todo
- default:
- //todo
- }