繁体   English   中英

案例 label 的常量值,用于 c 和 c++ 中的 switch 语句,但显示不同的行为

[英]constant value for case label for switch statement in c and c++ but show different behaviour

For same program in c and c++ when we use constant integer variable as case label it is valid only in c++ and not in c also when we use constant integer array member as case label then it is not valid for both c and 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;
    }
}

这种行为的主要原因是什么?

The main reason for this is the 2018 C standard says of case labels in 6.8.4.2 3 “The expression of each case label shall be an integer constant expression…” and defines an integer constant expression in 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. integer 常量表达式中的强制转换运算符只能将算术类型转换为 integer 类型,但作为sizeof_Alignof运算符的操作数的一部分除外。

而 2017 C++ 标准在 9.4.2 中提到case标签“常量表达式应是一个转换的常量表达式……”并在 8.20 中定义了一个转换的常量表达式,其中有四页文本涉及核心常量表达式integer 常量表达式等.

总之,C++ 标准更广泛地说明了在翻译时需要语言实现来评估什么。

术语“常量表达式”是用词不当。 更恰当的描述是,这些是语言实现在翻译程序时需要能够解析为特定值的表达式。 C++ 标准比 C 标准需要更多的实现。

6.8.4.2 switch 语句 p3:

each case label shall be an integer constant expression ,并且同一 switch 语句中的任何两个 case 常量表达式在转换后都不应具有相同的值。

6.6 常量表达式 p6:

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, and floating constants that are the immediate operands of casts.

如此定义的原因是能够静态计算代码中每个条件的偏移量。 否则,通过依次检查每个条件,与嵌套的一系列条件相比,它不会加快代码速度。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM