C++基础(15)关于 Switch Case 语句的要点

290 阅读2分钟

我报名参加金石计划1期挑战——瓜分10万奖池,这是我的第15篇文章,点击查看活动详情

1)  switch 中提供的表达式应该产生一个常量值,否则它将无效。switch case 的一些有效表达式将是,

// 允许常量表达式
switch(1+2+23) 
switch(1*2+3%4) 

// 允许变量表达式
// 它们被赋值为固定值
switch(a*b+c*d) 
switch( a+b+c)

2) 不允许有重复的大小写值。

3) 默认语句是可选的。即使 switch case 语句没有默认语句, 
它也可以毫无问题地运行。

4) break 语句用于在 switch 内部终止语句序列。当到达 break 语句时,switch 终止,控制流跳转到 switch 语句之后的下一行。

5) break 语句是可选的。如果省略,则执行将继续到下一个案例。控制流将传递到后续案例,直到达到中断为止。

6) switch 语句的嵌套是允许的,这意味着你可以在另一个 switch 中拥有 switch 语句。然而,应该避免嵌套的 switch 语句,因为它会使程序更复杂且可读性更低。 

7)  Switch 语句仅限于检查条件中的整数值和字符。
流程图:

image.png

示例 1:

演示switch语法的C程序

#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;
}

演示 switch 语法的 C++ 程序

#include <iostream>
using namespace std;

// 驱动程序代码
int main()
{
	int x = 2;
	switch (x) {
	case 1:
		cout << "Choice is 1";
		break;
	case 2:
		cout << "Choice is 2";
		break;
	case 3:
		cout << "Choice is 3";
		break;
	default:
		cout << "Choice other than 1, 2 and 3";
		break;
	}
	return 0;
}

输出

Choice is 2

时间复杂度: ******O(1)

辅助空间:  O(1)

示例 2:

演示switch语法的C程序

#include <stdio.h>

// 驱动程序代码
int main()
{
	char x = 'A';
	switch (x) {
	case 'A':
		printf("Choice is A");
		break;
	case 'B':
		printf("Choice is B");
		break;
	case 'C':
		printf("Choice is C");
		break;
	default:
		printf("Choice other than A, B and C");
		break;
	}
	return 0;
}

演示switch语法的C++程序

#include <iostream>
using namespace std;

// 驱动程序代码
int main()
{
	char x = 'A';
	switch (x) {
	case 'A':
		cout << "Choice is A";
		break;
	case 'B':
		cout << "Choice is B";
		break;
	case 'C':
		cout << "Choice is C";
		break;
	default:
		cout << "Choice other than A, B and C";
		break;
	}
	return 0;
}

输出

Choice is A

输出:

Choice is A

时间复杂度:  O(1)

辅助空间:  O(1)

switch 语句来演示具有唯一标签的多个案例

#include <stdio.h>

int main() {

char n='C';
switch(n)
{
	case 'A':
	case 'B':
	printf("A and B\n");
	break;
	
	case 'C':
	case 'D':
	printf("C and D\n");
	break;
	
	default:printf("Alphabet is greater than D\n");
	break;
}
return 0;
		
}

switch 语句来演示具有唯一标签的多个案例

#include <iostream>
using namespace std;

int main()
{
char n='C';
switch(n)
{
	case 'A':
	case 'B':
	cout<<"A and B"<<endl;
	break;
	
	case 'C':
	case 'D':
	cout<<"C and D"<<endl;
	break;
	
	default:cout<<"Alphabet is greater than D"<<endl;
	break;
}
return 0;
}

输出

C and D

 时间复杂度:O(1)

辅助空间:O(1)

如果大家在阅读我的文章的时候发现了一些错误,欢迎在评论区留言告诉我。我是一个正在学习C++的蒟蒻,关注我,我们一起加油。