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

5

8

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.

Lilley answered 8/1, 2011 at 19:10 Comment(0)
B
11

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.

Benjamin answered 8/1, 2011 at 19:13 Comment(0)
L
4

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:
        //
}
Livingston answered 8/1, 2011 at 19:14 Comment(0)
P
2

The problem here is you are using variables. You can only use constants in switch statements.

Do something like

#define SOME_VALUE 1

or

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

And you will be able to use valuea and so forth in your switch statement.

Phillada answered 8/1, 2011 at 19:12 Comment(2)
So I'll have to resort to if-else-if-else again? Isn't there a way around this?Lilley
Yes, use defines, whats the problem with that? :DPhillada
B
1

If your case values truly change at runtime, that's what the if...else if...else if construct is there for.

Bremble answered 8/1, 2011 at 19:25 Comment(0)
R
-2

or just do this

switch((int)secion)
Rascally answered 9/1, 2011 at 0:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.