holycatcrusher holycatcrusher - 4 years ago 83
C++ Question

use an int declared in class in a switch statement in one of the methods in the class

I am getting the error "this cannot be used in a constant expression." What I am trying to do should be quite a simple task. All I would like to be able to do is use a variable declared in a class in a switch statement that is within a method in the class. For example,

in the class

private:
int someValue;


in the class constructor

Classname::ClassName(){
someValue = 1;

}


in the method

ClassName::someMethod(){
int command = getCommandNumber();

switch (command){
case someValue:
doSomeStuff();
break;


}


}


In the method if I replace
someValue
with just the number
1
, everything works fine; however, if I use
someValue
, it won't compile, and it gives me the error stated above. How can I fix this. Thanks.

Answer Source

The case labels in a switch-statement requires constants known at compile time. someValue must either be something of the same order with constexpr; or some prvalue constant; or an enum or enum class . If you must use a runtime criteria, use an if-else ladder.

ClassName::someMethod(){
   int command = getCommandNumber();
        if(command == someValue)
            doSomeStuff();
        else if(command == ...)
            ....
   }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download