📜  C++中switch语句的case标签的数据类型?

📅  最后修改于: 2021-05-26 02:39:47             🧑  作者: Mango

在C++ switch语句中,每个case标签的表达式必须是整数常量表达式。

例如,以下程序编译失败。

/* Using non-const in case label */
#include
int main()
{
  int i = 10;
  int c = 10;
  switch(c) 
  {
    case i: // not a "const int" expression
         printf("Value of c = %d", c);
         break;
    /*Some more cases */
                     
  }
  return 0;
}

我使用const之前,可以使上述程序正常工作。

#include
int main()
{
  const int i = 10;
  int c = 10;
  switch(c) 
  {
    case i:  // Works fine
         printf("Value of c = %d", c);
         break;
    /*Some more cases */
                     
  }
  return 0;
}

注意:以上事实仅适用于C++。在C中,两个程序均产生错误。在C语言中,使用整数字面量不会导致错误。

程序使用切换大小写查找两个数字之间的最大数字:

#include
int main()
{
  int n1=10,n2=11;
  
  // n1 > n2 (10 > 11) is false so using  
  // logical operator '>', n1 > n2 produces 0
  // (0 means false, 1 means true) So, case 0 
  // is executed as 10 > 11 is false. Here we 
  // have used type cast to convert boolean to int, 
  // to avoid warning.
  
  switch((int)(n1 > n2)) 
  {
    case 0:  
         printf("%d is the largest\n", n2);
         break;
    default:
         printf("%d is the largest\n", n1);
  }
  
  // n1 < n2 (10 < 11) is true so using logical 
  // operator '<', n1 < n2 produces 1 (1 means true, 
  // 0 means false) So, default is executed as we
  // don't have case 1 to be executed.
  
  switch((int)(n1 < n2))
  {
    case 0:  
         printf("%d is the largest\n", n1);
         break;
    default:
         printf("%d is the largest\n", n2);
  }
  
  return 0;
}
//This code is contributed by Santanu
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。