2012-12-01 34 views
0

我試圖做到以下幾點:C++開關:case <some constant> - 這是允許的嗎?

switch(moveDirection){ 
     case MOVE_DIRECTION_UP: 
      //do something 
     break; 
    } 

哪裏MOVE_DIRECTION_UP是這樣的:

const unsigned char MOVE_DIRECTION_UP = 0x0; 

編譯器給出了錯誤:MOVE_DIRECTION_UP不能出現在常量表達式

當然這應該是允許,因爲如果我用0x0替換MOVE_DIRECTION_UP,它編譯得很好。

任何幫助表示讚賞,謝謝!

+0

哪個編譯器? g ++不會給我一個錯誤 – asheeshr

回答

2

如果您使用的是C++ 11,則可以將MOVE_DIRECTION_UP聲明爲constexpr。編譯器會將它視爲一個可用作開關標籤的常量值。

如果你沒有,你可以定義一個枚舉:

namespace eDirection { enum e { 
    UP = 0x0, 
    DOWN = 0x1 
};} 

switch(direction) { 
    case eDirection::UP: ... 
}; 
1

這是允許在C++中。你的代碼是正確的。可以在常量表達式中使用const變量。

你確定你正在構建一個C++源文件而不是C嗎?在C中,代碼無效(const變量不能用用於常量表達式中。)

0

這似乎是一個編譯器錯誤。

在C++ 98:

5.19 Constant expression

...

An integral constant-expression can involve only literals (2.13), enumerators, const variables or static data members of integral or enumeration types initialized with constant expressions (8.5)

在C++ 11:

5.19 Constant expressions

...

2 A conditional-expression is a core constant expression unless it involves one of the following as a potentially evaluated subexpression

...

— an lvalue-to-rvalue conversion (4.1) unless it is applied to

a glvalue of integral or enumeration type that refers to a non-volatile const object with a preceding initialization, initialized with a constant expression, or

0

您沒有提供您的問題表現出了實際的程序,所以我會用一個水晶球。你向前聲明瞭你的const,並且它的值不能直接在交換機上看到。