Оператор Switch
Оператор switch
також є однією з керуючих структур, яка спрощує прийняття рішень у ваших програмах на C++. Він забезпечує ефективний спосіб обчислення виразу і виконання різних блоків коду на основі значення цього виразу. Це може бути особливо зручно, коли ви маєте справу з великою кількістю умов розгалуження.
Передусім вона призначена для роботи з числовими значеннями, такими як цілі числа (int
) і символи (char
). І його синтаксис виглядає наступним чином:
cpp99123456789101112131415switch (вираз){case value1:// Код, що виконується, коли вираз співпадає зі значенням value1break;case value2:// Код, що виконується при співпадінні виразу зі значенням value2break;// За потреби можна додати більше випадківdefault:// Код для виконання, коли жодна з міток регістру не співпадає з виразом}
switch
123456789101112131415switch (expression) { case value1: // Code to execute when expression matches value1 break; case value2: // Code to execute when expression matches value2 break; // More cases can be added as needed default: // Code to execute when none of the case labels match the expression }
Suppose you own a restaurant and want to provide a menu based on numerical codes listed. Here's the code representation of the menu items.
main
1234567891011121314151617181920212223242526#include <iostream> int main() { // try to change the value int menu_number = 1; switch (menu_number) { case 1: std::cout << "Pizza" << std::endl; break; case 2: std::cout << "Burger with fries" << std::endl; break; case 3: std::cout << "Pasta with meatballs" << std::endl; break; default: std::cout << "We don`t have this in our menu" << std::endl; break; } }
Так, це можна зробити за допомогою простого оператора if
, і це буде виглядати приблизно так:
main
123456789101112131415161718192021222324#include <iostream> int main() { // try to change the value int menu_number = 1; if (menu_number == 1) { std::cout << "Pizza" << std::endl; } else if (menu_number == 2) { std::cout << "Burger with fries" << std::endl; } else if (menu_number == 3) { std::cout << "Pasta with meatballs" << std::endl; } else { std::cout << "We don`t have this in our menu" << std::endl; } }
Він працюватиме так само та так, як очікується, але зазвичай краще використовувати оператор switch
, оскільки він надає більш зрозумілий, читабельніший і, що найважливіше, легший для підтримки та масштабований спосіб керування цим видом потоку управління.
main
12345678910111213141516171819202122#include <iostream> int main() { // change the number and look how it affect the output int number = 3; switch (number) { case 1: std::cout << '1' << std::endl; case 2: std::cout << '2' << std::endl; case 3: std::cout << '3' << std::endl; case 4: std::cout << '4' << std::endl; case 5: std::cout << '5' << std::endl; break; } }
Swipe to start coding
- Write a
switch
statement that prints the corresponding day of the week based on the value ofday_of_week
. - If the value is not a valid day, output
The day doesn't exist
in the console.
Рішення
solution
Дякуємо за ваш відгук!
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат