2011-01-08 109 views
7

爲什麼不這項工作:爲什麼我不能在switch語句中使用NSInteger?

NSInteger sectionLocation = 0; 
NSInteger sectionTitles = 1; 
NSInteger sectionNotifications = 2; 

switch (section) { 
    case sectionLocation: 
     // 
     break; 
    case sectionTitles: 
     // 
     break; 
    case sectionNotifications: 
     // 
     break; 
    default: 
     // 
} 

我得到這個編譯錯誤:

error: case label does not reduce to an integer constant

是沒可能使用NSInteger的是這樣的?如果是這樣,是否有另一種方法在switch語句中使用變量作爲例子? sectionLocation等有可變值。

回答

10

問題不在於標量類型,而是當它們是這樣的變量時,案例標籤可能會更改值。

對於所有意圖和目的,編譯器將switch語句編譯爲一組goto。標籤不能變化。

使用枚舉類型或#defines。

2

這裏的問題是你使用的是變量。你只能在switch語句中使用常量。

這樣做

#define SOME_VALUE 1 

enum Values { 
    valuea = 1, 
    valueb = 2, 
    ... 
} 

而你,也就能夠使用值a等在switch語句。

+0

因此,我將不得不訴諸的if-else-if-else語句來着?這有沒有解決辦法? – Rits 2011-01-08 19:14:00

4

原因在於編譯器通常希望創建一個使用開關值作爲該表的鍵的「跳轉表」,並且只有在打開一個簡單的整數值時才能這樣做。這應該工作,而不是:

#define sectionLocation 0 
#define sectionTitles 1 
#define sectionNotifications 2 

int intSection = section; 

switch (intSection) { 
    case sectionLocation: 
     // 
     break; 
    case sectionTitles: 
     // 
     break; 
    case sectionNotifications: 
     // 
     break; 
    default: 
     // 
} 
1

如果你的情況確實值在運行時改變,這是什麼,如果...否則,如果...否則,如果結構是有。

-2

或只是這樣做

switch((int)secion)