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

Why this does not 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 compilation error:

error: case label does not come down to an integer constant

Is it impossible to use NSInteger? If so, is there another way to use variables as cases in a switch statement? sectionLocation etc. have variable values.

+7
source share
5 answers

The problem is not with the scalar type, but with the fact that case labels can change value when they are such variables.

In all senses and purposes, the compiler compiles the switch statement as a set of gotos. Labels cannot be variables.

Use an enumerated type or #defines.

+10
source

The reason is that the compiler often wants to create a "jump table" using the key value as the key in this table, and he can only do this by including 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: // } 
+4
source

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

Do something like

 #define SOME_VALUE 1 

or

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

And you can use valuea etc. in the switch statement.

+2
source

If the values โ€‹โ€‹of your case really change at run time, then what is if ... else if ... else if construct is for.

+1
source

or just do it

 switch((int)secion) 
-2
source

All Articles