Course Content
C++ Introduction
C++ Introduction
Switch Statement
A switch
statement is a control flow construct in programming used to execute one block of code out of multiple possible options, based on the value of a single variable or expression. It's a more structured and readable alternative to using multiple if-else
statements when comparing the same value to several possible options.
main
switch
#include <iostream> int main() { // Example user choice: 1 for Check Balance, 2 for Deposit, etc. int userOption = 1; // Simulating a banking system menu using a switch statement switch (userOption) { case 1: // Check account balance std::cout << "Checking account balance..." << std::endl; break; case 2: // Deposit money std::cout << "Depositing money into your account..." << std::endl; break; case 3: // Withdraw money std::cout << "Withdrawing money from your account..." << std::endl; break; case 4: // Exit std::cout << "Exiting the system. Thank you for banking with us!" << std::endl; break; default: // Invalid option std::cout << "Invalid option. Please choose a valid menu option." << std::endl; break; } }
-
break
- statement means an exit from a block of code; -
default
- is an optional part but a useful one. This part will be executed if none of the cases doesn't fit.
We check the userOption
variable. If it equals 1
, the corresponding text for checking the account balance will be displayed. The break
statement ensures that the program exits the entire switch-case
block after processing this case, preventing the execution of other cases.
The break keyword
However, there is an important aspect of the switch
statement to keep in mind. If the break
statement is intentionally removed from a case, the program will continue executing subsequent cases, even if their conditions do not match. This behavior, known as fall-through, can be useful in specific scenarios but may lead to unexpected results if not used carefully.
main
#include <iostream> int main() { // Example user choice: 1 for Check Balance, 2 for Deposit, etc. int userOption = 1; // Simulating a banking system menu using a switch statement switch (userOption) { case 1: // Check account balance std::cout << "Checking account balance..." << std::endl; case 2: // Deposit money std::cout << "Depositing money into your account..." << std::endl; case 3: // Withdraw money std::cout << "Withdrawing money from your account..." << std::endl; case 4: // Exit std::cout << "Exiting the system. Thank you for banking with us!" << std::endl; default: // Invalid option std::cout << "Invalid option. Please choose a valid menu option." << std::endl; } }
Without the break
command, the program flow will ignore all the following checks and simply execute the commands of the following cases until it encounters the break
statement or the end of the entire switch
block.
Thanks for your feedback!