Home  >  Article  >  Backend Development  >  Usage of switch statement in c++

Usage of switch statement in c++

下次还敢
下次还敢Original
2024-05-09 03:42:20544browse

The switch statement in C is a selection construct used to execute different blocks of code based on the value of a variable or expression, converting multiple if-else statements into more concise code. Its usage includes: specifying an expression to evaluate. Add multiple case statements for the constant or literal values ​​to be matched. Each case statement must be followed by a break statement. Optionally add a default statement to be executed if there is no matching case.

Usage of switch statement in c++

Usage of switch statement in C

The switch statement is a selection structure that is based on a variable or expression The value executes different blocks of code. It's an efficient way to convert multiple if-else statements into cleaner and shorter code.

Grammar:

<code class="cpp">switch (expression) {
    case value1:
        // 代码块 1
        break;
    case value2:
        // 代码块 2
        break;
    ...
    default:
        // 如果没有匹配的 case,执行此代码块
}</code>

Usage details:

  • expression: To be evaluated variable or expression.
  • value1, value2, ...: represents the constant or literal value to be matched.
  • case: is used to specify the code block to be executed. Each case must contain a break statement to exit the switch statement.
  • default: Optional, a code block that is executed when there is no matching case.

Note:

  • expression must be an integer or enumeration type.
  • value1, value2, etc. must be compatible with the type of expression.
  • The order of case statements does not matter, but is usually organized by value size.
  • You can omit the break statement through the fallthrough keyword to execute multiple consecutive code blocks.

Example:

The following example demonstrates how to use the switch statement in C:

<code class="cpp">int day = 3;

switch (day) {
    case 1:
        cout << "星期一" << endl;
        break;
    case 2:
        cout << "星期二" << endl;
        break;
    case 3:
        cout << "星期三" << endl;
        break;
    case 4:
        cout << "星期四" << endl;
        break;
    case 5:
        cout << "星期五" << endl;
        break;
    default:
        cout << "无效的日期" << endl;
}</code>

In this case, when day A value of 3 causes the switch statement to execute the "Wednesday" block of code.

The above is the detailed content of Usage of 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