Home >Backend Development >C++ >How to use switch statement in c++
The switch statement is a control flow statement used to execute different blocks of code based on the value of a variable or expression. The syntax is: switch (variable) { case value1: // Code block for value 1 break; ... default: // Default code block to be executed if the variable does not match any case }. It is often used to select actions based on values, select code paths based on state or input, or create menu-driven programs.
The switch statement in C
What is the switch statement?
The switch statement is a control flow statement used to execute different blocks of code based on the value of a variable or expression.
Syntax:
<code class="cpp">switch (variable) { case value1: // 针对值 1 的代码块 break; case value2: // 针对值 2 的代码块 break; ... default: // 如果变量不匹配任何 case,则执行的默认代码块 }</code>
Working principle:
Usage:
The switch statement is usually used in the following situations:
Example:
The following example shows how to use a switch statement to perform different actions based on user input:
<code class="cpp">#include <iostream> int main() { int choice; std::cout << "请选择以下选项:" << std::endl; std::cout << "1. 添加" << std::endl; std::cout << "2. 减法" << std::endl; std::cout << "3. 乘法" << std::endl; std::cout << "4. 除法" << std::endl; std::cin >> choice; switch (choice) { case 1: // 执行加法操作 break; case 2: // 执行减法操作 break; case 3: // 执行乘法操作 break; case 4: // 执行除法操作 break; default: // 输入无效 std::cout << "无效选项" << std::endl; } return 0; }</code>
The above is the detailed content of How to use switch statement in c++. For more information, please follow other related articles on the PHP Chinese website!