c++ - 我可以在 case 语句中使用数组吗?

标签 c++ arrays switch-statement case

我想在 C++ 的 switch/case 语句中使用一个 const int 数组。是否可以?到目前为止,我已经尝试过类似的方法:

int main()
{
    int const tab[3] = {1,2,3};
    int value(2);
    switch(value)
    {
        case tab[1]:
            cout << "result is: " << tab[0]<< endl;
    }
    return 0;
}

但是编译器一直告诉我:

.../main.cpp|11|error: the value of ‘tab’ is not usable in a constant expression

好吧,我将我的数组声明为“int const”,这还不够吗?

最佳答案

每个 case 语句都必须采用一个常量表达式,其定义为:

A conditional-expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine (1.9), would evaluate one of the following expressions:

  • [...]
  • an lvalue-to-rvalue conversion (4.1) unless it is applied to
    • a non-volatile glvalue of integral or enumeration type that refers to a non-volatile const object with a preceding initialization, initialized with a constant expression [ Note: a string literal (2.14.5) corresponds to an array of such objects. —end note ], or
    • a non-volatile glvalue that refers to a non-volatile object defined with constexpr, or that refers to a non-mutable sub-object of such an object, or
    • a non-volatile glvalue of literal type that refers to a non-volatile object whose lifetime began within the evaluation of e;
  • [...]

您的情况是左值到右值的转换,但这三个要点都不适用,因此 tab[1] 不是核心常量表达式。然而,第二个子项目符号点为我们提供了一个线索:如果对象是用 constexpr 定义的会怎样!这将使 tab[1] 成为一个常量表达式,因此,编译:

constexpr int tab[3] = {1,2,3};
int value(2);
switch(value)
{
    case tab[1]:
        cout << "result is: " << tab[0]<< endl;
}

const 不会使对象成为常量表达式。它只是使它不可变。请注意,以下是完全有效的代码:

int x;
cin >> x;
const int y = x; // obviously, y can't be a constant expression

关于c++ - 我可以在 case 语句中使用数组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30549819/

相关文章:

r - 类似开关的问卷评分功能

c++ - 将函数作为模板参数传递给成员函数

java - 在 while 循环中使用 switch 语句

c++ - 在不同波形格式之间转换 (WAVEFORMATEX)

c++ - C++ 中结构的大小 (sizeof) 与数组的实际大小不对应

javascript - JSON 到数组不工作

javascript - 用另一个对象数组过滤对象数组,并为匹配的对象添加额外的键

C# 开关与 VB 案例语句

c++ - 使用 Eclipse 创建动态加载的 Linux 库

c++ - 使用 PostMessage 与 SendNotifyMessage 广播到拥有的窗口