Can an array be used in a case expression?

I would like to use a const int array in a switch / case statement in C ++. Is it possible? So far I have tried something like:

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;
}

      

However, the compiler keeps telling me:

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

      

Well, I declared my array as "int const", right?

+3


source to share


2 answers


Each statement case

must accept a constant expression, which is defined as:

A conditional expression e is a constant constant expression if evaluating e, following the rules of the abstract machine (1.9), evaluates one of the following expressions:

  • [...]
  • lvalue-to-rvalue conversion (4.1) if not applied to
    • non-volatile glvalue of an integral or enumerated type that refers to a non-volatile const object with a previous initialization, initialized with a constant expression [Note: a string literal (2.14.5) matches an array of such objects. -end note] or
    • a volatile glvalue that refers to a non-volatile object defined with constexpr

      , or which refers to a non-volatile sub-object of such an object, or
    • a nonvolatile literal glvalue that refers to a nonvolatile object that began its lifespan as part of the e score;
  • [...]

Your case is an lvalue-to-rvalue conversion, but none of these three bullet points apply, so tab[1]

it is not a basic constant expression. However, this second point of the subpool gives us a clue: what if the object was defined with constexpr

! This would make it a tab[1]

constant expression, and thus this would compile:



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

      

const

does not make the object a constant expression. It just makes it non-mutable. Please note that the code below is fully valid:

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

      

+6


source


No, you don't need const

, you need constexpr

. Rewrite your code with:

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;
}

      



Since you need tab

the compile-time value , it must be an expression constexpr

. Also, each operator case

accepts a constant expression not a constant value. const

will make it a constant value, whereas it constexpr

will make it a constant expression.

+2


source







All Articles