C - 嵌套 Switch 语句
可以将 switch 语句作为外部 switch 语句序列的一部分。即使内外 switch 的 case 常量包含相同的值,也不会发生冲突。
语法
嵌套 Switch 语句的语法如下 -
switch(ch1){ case 'A': printf("This A is part of outer switch" ); switch(ch2) { case 'A': printf("This A is part of inner switch" ); break; case 'B': /* case code */ } break; case 'B': /* case code */ }
示例
请看以下示例 -
#include <stdio.h> int main (){ /* 局部变量定义 */ int a = 100; int b = 200; switch(a){ case 100: printf("This is part of outer switch ", a); switch(b){ case 200: printf("This is part of inner switch ", a); } } printf("Exact value of a is: %d ", a); printf("Exact value of b is: %d ", b); return 0; }
输出
编译并执行上述代码后,将产生以下输出 -
This is part of outer switch This is part of inner switch Exact value of a is : 100 Exact value of b is : 200
C 语言中嵌套的 Switch-Case 语句
就像嵌套 ifelse 一样,您可以嵌套 switch-case 结构。您可以在外部 switch 作用域的一个或多个 case 标签的代码块内分别使用不同的 switch-case 结构。
switch-case 的嵌套可以按如下方式进行 -
switch (exp1){ case val1: switch (exp2){ case val_a: stmts; break; case val_b: stmts; break; } case val2: switch (expr2){ case val_c: stmts; break; case val_d: stmts; break; } }
示例
这是一个简单的程序,用于演示 C 语言中嵌套 Switch 语句的语法 -
#include <stdio.h> int main(){ int x = 1, y = 'b', z='X'; // Outer Switch switch (x){ case 1: printf("Case 1 "); switch (y){ case 'a': printf("Case a "); break; case 'b': printf("Case b "); break; } break; case 2: printf("Case 2 "); switch (z){ case 'X': printf("Case X "); break; case 'Y': printf("Case Y "); break; } } return 0; }
输出
运行此代码时,将产生以下输出 -
Case 1 Case b
更改变量(x、y 和 z)的值,然后再次检查输出。输出取决于这三个变量的值。