Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use an NSInteger in a switch statement?

Why doesn't this work:

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

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

I get this compile error:

error: case label does not reduce to an integer constant

Is it not possible to use NSInteger's like this? If so, is there another way to use variables as cases in a switch statement? sectionLocation etc. have variable values.

like image 613
Rits Avatar asked Jan 08 '11 19:01

Rits


2 Answers

The problem isn't the scalar type, but that the case labels may change value when they are variables like that.

For all intents and purposes, the compiler compiles a switch statement as a set of gotos. The labels can't be variable.

Use an enumerated type or #defines.

like image 128
bbum Avatar answered Sep 20 '22 17:09

bbum


The reason is that the compiler will often want to create a 'jump table' using the switch value as the key into that table and it can only do that if it's switching on a simple integer value. This should work instead:

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

int intSection = section;

switch (intSection) {
    case sectionLocation:
        //
        break;
    case sectionTitles:
        //
        break;
    case sectionNotifications:
        // 
        break;
    default:
        //
}
like image 20
trojanfoe Avatar answered Sep 18 '22 17:09

trojanfoe