Search code examples
c++c++11switch-statementconstantsconstexpr

switch-case error | the value of is not usable in a constant expression


I wrote a simple example to solve the problems I faced when writing his program.

During program execution I get values of input1 and input2 when returning values from functions, which are then never change. Then a little later after various computations in the process of the program I get a result which is also no longer changeable.

I'm trying to compare them using switch-case, but I get one error "the value of ‘input1’ is not usable in a constant expression".

#include <iostream>

using namespace std;

char getChar()
{
    char c;
    cin >> c;
    return c;
}

int main()
{
    // it doesn't work
    const char input1 = getChar();
    const char input2 = getChar();

    // it it works
    //const char input1 = 'R';
    //const char input2 = 'X';

    char result = getChar();
    switch(result)
    {
        case input1:
            cout << "input1" << endl;
            break;
        case input2:
            cout << "input2" << endl;
            break;
    }
    return 0;
}

Solution

  • You have to have your case statements known at compile time. I.e.

    switch(result)
        {
            case 1:
                cout << "input1" << endl;
                break;
            case 2:
                cout << "input2" << endl;
                break;
        }
    

    These lines, whilst const only really mean read-only and are not initialised at compile time.

    // it doesn't work
    const char input1 = getChar();
    const char input2 = getChar();
    

    The reason the following two lines would work is because the compiler just substitues in X & R into your switch statement before your code even runs

    // it it works
    //const char input1 = 'R';
    //const char input2 = 'X';
    

    I would suggest changing your switch to an if statement

    if(input1)
    {}
    else if(intput2)
    {}
    

    The following code should work:

    #include <iostream>
    
    using namespace std;
    
    char getChar()
    {
        char c;
        cin >> c;
        return c;
    }
    
    int main()
    {
        // it doesn't work
        const char input1 = getChar();
        const char input2 = getChar();
    
        // it it works
        //const char input1 = 'R';
        //const char input2 = 'X';
    
        char result = getChar();
        if(result == input1){
                cout << "input1" << endl;
        }
        else if(result == input2){
                cout << "input2" << endl;
        }
    
        return 0;
    }