2011-01-08 114 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)