Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I can't use unsigned short in switch/case?

Tags:

c++

c

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.

like image 696
huahsin68 Avatar asked Nov 29 '22 18:11

huahsin68


1 Answers

C++ requires the case to have a constant-expression as its argument. What does that mean? It means that the only operands that are legal in constant expressions are:

  • Literals
  • Enumeration constants
  • Values declared as const that are initialized with constant expressions
  • sizeof expressions

In 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,

class ClsA {
    public:
        static const unsigned short m_var1 = 13;
        static const unsigned short m_var2 = 42;
};

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).

like image 200
Michael Foukarakis Avatar answered Dec 16 '22 10:12

Michael Foukarakis