I have two static member declarations in ClsA, like this:
class ClsA {
public:
static unsigned short m_var1;
static unsigned short m_var2;
};
unsigned short ClsA::m_var1 = 1001;
unsigned short ClsA::m_var2 = 1002;
In ClsB, I use those static member declarations from ClsA like this:
unsigned short var1; // assume var1 is declare/use some where in the code.
switch( var1 ) {
case ClsA::m_var1: // Error: cannot appear in a constant-expression
break;
case ClsB::m_var2: // Error: cannot appear in a constant-expression
break;
}
Why do I get an error if I use that in a switch statement? There is no error if I use it in an if statement.
C++ requires the
caseto have a constant-expression as its argument. What does that mean? It means that the only operands that are legal in constant expressions are:constthat are initialized with constant expressionssizeofexpressionsIn your case, if you declared your static members as
const, and initialized them when declared with an integral constant expression, you could use them in switch-case statements. For example,If, on the other hand, you insist on switching on a variable to avoid multiple if-else if statements, I would suggest using a jump table (it’s also referred as a lookup table).