简体   繁体   中英

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

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

尝试

static const unsigned short m_var1;

m_var1 and m_var2 aren't constants. But the cases in switch have to be constant expressions (1, 4*8, some_const+1).

It's because the expressions after the case keyword must be a compile time constants and your m_var1 and m_var2 arent. If need to do this kind of test, use an if chain.

http://gcc.gnu.org/ml/gcc-help/2005-12/msg00069.html talks about this error.

The values must be compile time constants as the error message indicates. They should be declared and defined as const inside the class declaration, such that the compiler knows about them and their values at any point of compilation, typically in a header file.

class ClsA {
public:
   static unsigned short const m_var1 = 1001;
   static unsigned short const m_var2 = 1002;
};

In some object file you should then also instantiate these const variables

unsigned short const ClsA::m_var1;
unsigned short const ClsA::m_var2;

that is without repeating the initialization value and without the static keyword.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM