Home >Backend Development >C++ >How to write the range after case of switch statement in c++
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.
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>
Syntax structure:
<code>case 范围: // 代码块 break;</code>
Explanation:
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>
Output:
<code>数字介于 1 和 5 之间</code>
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!