Objective-C 嵌套 switch 语句

可以将 switch 作为外部 switch 语句序列的一部分。即使内部和外部 switchcase 常量包含公共值,也不会产生冲突。


语法

嵌套 switch 语句的语法如下:

  1. switch(ch1) {
  2. case 'A':
  3. printf("This A is part of outer switch" );
  4. switch(ch2) {
  5. case 'A':
  6. printf("This A is part of inner switch" );
  7. break;
  8. case 'B': /* case code */
  9. }
  10. break;
  11. case 'B': /* case code */
  12. }

实例

  1. #import <Foundation/Foundation.h>
  2. int main () {
  3. /* local variable definition */
  4. int a = 100;
  5. int b = 200;
  6. switch(a) {
  7. case 100:
  8. NSLog(@"This is part of outer switch\n", a );
  9. switch(b) {
  10. case 200:
  11. NSLog(@"This is part of inner switch\n", a );
  12. }
  13. }
  14. NSLog(@"Exact value of a is : %d\n", a );
  15. NSLog(@"Exact value of b is : %d\n", b );
  16. return 0;
  17. }

结果如下:

  1. 2022-07-07 22:09:20.947 demo[21703] This is part of outer switch
  2. 2022-07-07 22:09:20.948 demo[21703] This is part of inner switch
  3. 2022-07-07 22:09:20.948 demo[21703] Exact value of a is : 100
  4. 2022-07-07 22:09:20.948 demo[21703] Exact value of b is : 200

分类导航