In C, the switch-case statement is used to execute different blocks of code based on the value of an expression: 1. The expression can be an integer, character, or enumeration constant. 2. The case branch specifies the value of the expression to be matched. There can be multiple cases matching the same value. 3. Each case branch is followed by a block of code that needs to be executed, ending with a break statement. 4. The default branch is used to match values that are not specified in the expression. If there is no matching case, this code block is executed.
Usage of switch-case statement in C
Question: How to use switch-case statement in C Use switch-case statements?
Answer:
A switch-case statement is a conditional statement that is used to execute different blocks of code based on the value of an expression. The syntax is as follows:
<code class="cpp">switch (expression) { case value1: // 执行代码块 1 break; case value2: // 执行代码块 2 break; // ... default: // 可选的默认 case,如果没有匹配的 case,则执行此代码块 break; }</code>
Usage:
Example:
The following code uses a switch-case statement to perform different actions based on the characters entered by the user:
<code class="cpp">char ch; cout << "输入一个字符:"; cin >> ch; switch (ch) { case 'a': case 'A': cout << "您输入的是大写或小写的 A" << endl; break; case 'b': case 'B': cout << "您输入的是大写或小写的 B" << endl; break; default: cout << "您输入的不是 A 或 B" << endl; }</code>
The above is the detailed content of Usage of switch case in c++. For more information, please follow other related articles on the PHP Chinese website!