1. 主页
  2. 文档
  3. C语言教程
  4. C语言控制语句
  5. C中的switch语句

C中的switch语句

Switch 是一个控制语句,它允许一个值更改执行控制。

// Following is a simple program to demonstrate syntax of switch.
#include <stdio.h>
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 <stdio.h>
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 也可以在 switch 中使用

2) 匹配 case 之后的所有语句都会执行,直到到达 break 语句。

// There is no break in all cases
#include <stdio.h>
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 <stdio.h>
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)默认块可以放在任何地方。default 的位置无关紧要,如果没有找到匹配项,它仍然会执行。

// The default block is placed above other cases.
#include <stdio.h>
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 <stdio.h>
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) 上面写的case语句永远不会执行switch语句之后,控制权转移到匹配的case,case之前写的语句不被执行。

// Statements before all cases are never executed
#include <stdio.h>
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)两个case标签不能有相同的值

// Program where two case labels have same value
#include <stdio.h>
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
这篇文章对您有用吗?