Home  >  Article  >  Backend Development  >  How to use switch statement in c++

How to use switch statement in c++

下次还敢
下次还敢Original
2024-04-28 19:24:171105browse

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.

How to use switch statement in c++

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:

  • variable is to be checked variable or expression. The
  • case statement specifies each value to match. The
  • break statement is used to exit the current case block and continue executing subsequent code.
  • default block is optional and is used to handle all values ​​that do not match any case.

Usage:

The switch statement is usually used in the following situations:

  • Select different operations based on the value.
  • Select different code paths based on status or input.
  • Create menu-driven programs.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to use setw in c++Next article:How to use setw in c++