switch ကို တန်ဖိုးတစ်ခုအပေါ်မူတည်ပြီး case များစွာထဲက တစ်ခုကို ရွေး run ဖို့ သုံးပါတယ်။ Menu option, day number, command code လို fixed value တွေကို handle လုပ်တဲ့အခါ if...else ထက် ပိုဖတ်ရလွယ်ပါတယ်။
cpp
#include <iostream>
using namespace std;
int main() {
int option = 2;
switch (option) {
case 1:
cout << "Create new file";
break;
case 2:
cout << "Open existing file";
break;
case 3:
cout << "Exit program";
break;
default:
cout << "Invalid option";
}
return 0;
}option တန်ဖိုးက 2 ဖြစ်လို့ case 2 ကို run လုပ်ပါတယ်။ break က matched case ပြီးတာနဲ့ switch ထဲကနေ ထွက်စေပါတယ်။ default က ဘယ် case နဲ့မှ မကိုက်ရင် run မယ့် fallback ပါ။
You should see
Open existing fileInfo
break မထည့်ရင် နောက် case တွေကို ဆက် run သွားနိုင်ပါတယ်။ တချို့အခါ intentional ဖြစ်နိုင်ပေမယ့် beginner အတွက် bug ဖြစ်တာများပါတယ်။