'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 1:[1]

the case label requires somenthin known at compile time. A variable cannot work in this context. You will need an if... else if... else if... to mimic a switch statement with variable runtime values

Solution 2:[2]

The labels used in case statements have to be available to the compiler at compile-time, so what you're attempting won't work.

You've made it const, but that just means that it won't change once it's initialized.

Solution 3:[3]

Here I give another example of not able to use case statement. Just a code fragment.

switch (val) {
  case SOMECLASS::CONST_X:
     sosomething();
     break;

If CONST_X, say static const int CONST_X; If you define it in the header then the case statement is fine. But if defined in the implementation file (*.cpp), then you will not be able to pass the compiler. However, if you define in the header, sometime you will have linking issues. So my experience told me not use class constants (usually int type) in case statements.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gian Paolo
Solution 2 Steve
Solution 3 Kemin Zhou