开发者

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


Try

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜