gpt4 book ai didi

c++ - c和c++中switch语句的case标签的常量值,但显示不同的行为

转载 作者:行者123 更新时间:2023-12-02 10:13:17 25 4
gpt4 key购买 nike

对于c和c++中的同一程序,当我们使用常量整数变量作为大小写标签时,它仅在c++中有效,而在c中,当我们使用常量整数数组成员作为大小写标签时,则对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;
}
}

最佳答案

What is the main reason for this behaviour ?


主要原因是2018年C标准在6.8.4.2 3中提到 case标签。“每个 case标签的表达式应为整数常量表达式…”,并在6.6 6中定义了整数常量表达式:

An integer constant expression shall have integer type and shall only have operands that are integer constants, enumeration constants, character constants, sizeof expressions whose results are integer constants, _Alignof expressions, and floating constants that are the immediate operands of casts. Cast operators in an integer constant expression shall only convert arithmetic types to integer types, except as part of an operand to the sizeof or _Alignof operator.


而2017 C++标准在9.4.2中提到了 case标签,“常量表达式应为转换后的常量表达式……”,并在8.20中定义了转换后的常量表达式,其中四页文字涉及核心常量表达式,整数常量表达式等。 。
总而言之,C++标准在翻译时需要评估其语言实现的范围更为广泛。
术语“恒定表达”是误称。更恰当的描述是这些是语言实现在翻译程序时必须能够解析为特定值的表达。与C标准相比,C++标准需要更多的实现。

关于c++ - c和c++中switch语句的case标签的常量值,但显示不同的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62741509/

25 4 0