📜  C++中的嵌套switch语句

📅  最后修改于: 2021-05-30 02:50:12             🧑  作者: Mango

切换案例语句

这些替代了将变量与多个整数值进行比较的long if语句

  • switch语句是多路分支语句。它提供了一种简单的方法,可以根据表达式的值将执行分派到代码的不同部分。
  • Switch是一个控制语句,它允许一个值更改执行控制。

句法:

switch (n)
{
    case 1: // code to be executed if n = 1;
  break;
    case 2: // code to be executed if n = 2;
  break;
    default: // code to be executed if 
      // n doesn't match any cases
}

嵌套开关语句:

嵌套Switch语句引用另一个Switch语句内的Switch语句。

句法:

switch(n)
{
  // code to be executed if n = 1;
  case 1: 
    
  // Nested switch
  switch(num) 
  {
    // code to be executed if num = 10
    case 10: 
      statement 1;
      break;
      
    // code to be executed if num = 20
    case 20: 
      statement 2;
      break;
      
    // code to be executed if num = 30
    case 30: 
      statement 3;
      break;
      
      // code to be executed if n 
      // doesn't match any cases
      default: 
  }
  
  
  break;
    
  // code to be executed if n = 2;
  case 2:
    statement 2;
    break;
  
  // code to be executed if n = 3;
  case 3: 
    statement 3;
    break;
  
   // code to be executed if n doesn't match any cases
   default: 
}

例子:

// Following is a simple program to demonstrate
// syntax of Nested Switch Statements.
  
#include 
using namespace std;
  
int main()
{
    int x = 1, y = 2;
  
    // Outer Switch
    switch (x) {
  
    // If x == 1
    case 1:
  
        // Nested Switch
  
        switch (y) {
  
        // If y == 2
        case 2:
            cout << "Choice is 2";
            break;
  
        // If y == 3
        case 3:
            cout << "Choice is 3";
            break;
        }
        break;
  
    // If x == 4
    case 4:
        cout << "Choice is 4";
        break;
  
    // If x == 5
    case 5:
        cout << "Choice is 5";
        break;
  
    default:
        cout << "Choice is other than 1, 2 3, 4, or 5";
        break;
    }
    return 0;
}
输出:
Choice is 2
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”