【发布时间】:2020-07-05 13:45:20
【问题描述】:
对于 c 和 c++ 中的相同程序,当我们使用常量整数变量作为 case 标签时,它仅在 c++ 中有效,而在 c 中无效,当我们使用常量整数数组成员作为 case 标签时,它对 c 和 c++ 都无效.这种行为的主要原因是什么?
//for c
#include <stdio.h>
int main()
{
const int a=90;
switch(90)
{
case a://error : case label does not reduce to an integer constant
printf("error");
break;
}
const int arr[3]={88,89,90};
switch(90)
{
case arr[2]://error : case label does not reduce to an integer constant
printf("Error");
break;
}
}
//for c++
#include <stdio.h>
int main()
{
const int a=90;
switch(90)
{
case a:
printf("No error");
break;
}
const int arr[3]={88,89,90};
switch(90)
{
case arr[2]://error 'arr' cannot appear in a constant-expression
printf("Error");
break;
}
}
【问题讨论】:
-
这种行为的原因是 C 和 C++ 各自认为是常量表达式。
-
尽管有一些非常相似的语法,但 C 和 C++ 是两种 非常 不同的语言,具有不同的语义和行为,通常用于看起来非常相似的事物。这是 C 和 C++ 不同的一种情况。
标签: c++ c switch-statement constants