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
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:
Note:
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!