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

Can I use an array in a case statement?

我想在 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",这还不够吗?

不,你不需要 const,你需要 constexpr。用 :

重写你的代码
int main()
{
    constexpr int tab[3] = {1,2,3};
    int value(2);
    switch(value)
    {
        case tab[1]:
            cout << "result is: " << tab[0]<< endl;
    }
    return 0;
}

因为您在编译时需要 tab 的值,所以它应该是 constexpr 表达式。此外,每个 case 语句采用 constant-expression not constant-valueconst 将使其成为 constant-value,而 constexpr 将使其成为 constant-expression.

每个 case 语句必须采用 constant-expression,其定义为:

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;
  • [...]

您的情况是左值到右值的转换,但是这三个要点中的 none 适用,因此 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