吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C语言教程 → C++中switch语句的case标签的数据类型

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

来源:网络 | 更新时间:2022-01-14 07:48:16
在 C++ switch 语句中,每个 case 标签的表达式必须是整数常量表达式。  例如,以下程序编译失败。 
/* Using non-const in case label */
#include<stdio.h>
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放在i之前使上述程序工作。
#include<stdio.h>
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 中,使用整数文字不会导致错误。 使用 switch case 查找两个数之间的最大数的程序:
#include<stdio.h>
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 largestn", n2);
break;
default:
printf("%d is the largestn", 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 largestn", n1);
break;
default:
printf("%d is the largestn", n2);
}

return 0;
}
 

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com