Home > Backend Development > C++ > body text

How to write the range after case of switch statement in c++

下次还敢
Release: 2024-05-08 02:18:15
Original
298 people have browsed it

The case range of the switch statement in C is used to specify the value or value range that the variable can match. The syntax structure is: case range: // Code block break; It allows the code block to be executed when the variable matches the range, and uses The break statement exits the switch statement.

How to write the range after case of switch statement in c++

The switch statement case range in C

In C, the switch statement can be used to perform different executions based on the value of a variable code block. The scope after case is used to specify a specific value or range of values ​​that the variable can match. To specify a range, you need to use the tilde (~), as shown below:

<code class="cpp">switch (variable) {
    case value1 ~ value2:
        // 代码块
        break;
    // ...
}</code>
Copy after login

Syntax structure:

<code>case 范围:
     // 代码块
     break;</code>
Copy after login

Explanation:

  • Range: Specified using the tilde (~) to indicate the range that the variable can match.
  • Code block: Code that is executed when the variable matches the scope.
  • break: Optional end statement, used to exit the switch statement. Without break, the program will continue to execute the following cases.

Example:

<code class="cpp">int number = 5;

switch (number) {
    case 1 ~ 5:
        cout << "数字介于 1 和 5 之间" << endl;
        break;
    case 6:
        cout << "数字是 6" << endl;
        break;
    default:
        cout << "数字大于 6" << endl;
}</code>
Copy after login

Output:

<code>数字介于 1 和 5 之间</code>
Copy after login

In this example, the variable number# The value of ## (5) matches the range 1 ~ 5, so the first code block is executed.

The above is the detailed content of How to write the range after case of switch statement in c++. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
c++
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!