前提条件– C语言中的switch语句
Switch是一个控制语句,它允许一个值更改执行控制。
// Following is a simple program to demonstrate syntax of switch.
#include
int main()
{
int x = 2;
switch (x)
{
case 1: printf("Choice is 1");
break;
case 2: printf("Choice is 2");
break;
case 3: printf("Choice is 3");
break;
default: printf("Choice other than 1, 2 and 3");
break;
}
return 0;
}
输出:
Choice is 2
以下是有关switch语句的一些有趣事实。
1)switch中使用的表达式必须是整数类型(int,char和enum)。不允许使用任何其他类型的表达式。
// float is not allowed in switch
#include
int main()
{
float x = 1.1;
switch (x)
{
case 1.1: printf("Choice is 1");
break;
default: printf("Choice other than 1, 2 and 3");
break;
}
return 0;
}
输出:
Compiler Error: switch quantity not an integer
在Java,开关中也允许使用String(请参阅此)
2)匹配大小写之后的所有语句都将执行,直到到达break语句为止。
// There is no break in all cases
#include
int main()
{
int x = 2;
switch (x)
{
case 1: printf("Choice is 1\n");
case 2: printf("Choice is 2\n");
case 3: printf("Choice is 3\n");
default: printf("Choice other than 1, 2 and 3\n");
}
return 0;
}
输出:
Choice is 2
Choice is 3
Choice other than 1, 2 and 3
// There is no break in some cases
#include
int main()
{
int x = 2;
switch (x)
{
case 1: printf("Choice is 1\n");
case 2: printf("Choice is 2\n");
case 3: printf("Choice is 3\n");
case 4: printf("Choice is 4\n");
break;
default: printf("Choice other than 1, 2, 3 and 4\n");
break;
}
printf("After Switch");
return 0;
}
输出:
Choice is 2
Choice is 3
Choice is 4
After Switch
3)默认块可以放置在任何地方。默认位置无关紧要,如果找不到匹配项,则仍将执行默认位置。
// The default block is placed above other cases.
#include
int main()
{
int x = 4;
switch (x)
{
default: printf("Choice other than 1 and 2");
break;
case 1: printf("Choice is 1");
break;
case 2: printf("Choice is 2");
break;
}
return 0;
}
输出:
Choice other than 1 and 2
4)标签中使用的整数表达式必须是常量表达式
// A program with variable expressions in labels
#include
int main()
{
int x = 2;
int arr[] = {1, 2, 3};
switch (x)
{
case arr[0]: printf("Choice 1\n");
case arr[1]: printf("Choice 2\n");
case arr[2]: printf("Choice 3\n");
}
return 0;
}
输出:
Compiler Error: case label does not reduce to an integer constant
5)永远不会执行以上情况下编写的语句switch语句之后,控制权转移到匹配的情况下,不执行之前编写的语句。
// Statements before all cases are never executed
#include
int main()
{
int x = 1;
switch (x)
{
x = x + 1; // This statement is not executed
case 1: printf("Choice is 1");
break;
case 2: printf("Choice is 2");
break;
default: printf("Choice other than 1 and 2");
break;
}
return 0;
}
输出:
Choice is 1
6)两个案例标签不能具有相同的值
// Program where two case labels have same value
#include
int main()
{
int x = 1;
switch (x)
{
case 2: printf("Choice is 1");
break;
case 1+1: printf("Choice is 2");
break;
}
return 0;
}
输出:
Compiler Error: duplicate case value
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。