17

I use this code to set my constants

// Constants.h
extern NSInteger const KNameIndex;

// Constants.m
NSInteger const KNameIndex = 0;

And in a switch statement within a file that imports the Constant.h file I have this:

switch (self.sectionFromParentTable) {
    case KNameIndex:
        self.types = self.facilityTypes;
        break;
    ...

I get error at compile that read this: "error:case label does not reduce to an integer constant"

Any ideas what might be messed up?

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
Dan Morgan
  • 2,500
  • 5
  • 25
  • 32

5 Answers5

22

For C/C++ and Objective-C must the case statement have fixed values - "reduced to an integer (read value)" at compile time

Your constants is not a real "constant" because it is a variable and I imagine it can be changed through a pointer - ie &KNameIndex

Usually one defines constants as enum

enum {
    KNameIndex = 0,
    kAnotherConstant = 42
};

If you would use C++, or Objective-C++ (with .mm as file extension) you could use a const statement as

const int KNameIndex = 0;
epatel
  • 45,805
  • 17
  • 110
  • 144
  • The const statement is perfectly legal in Objective-C, and perfectly operational with NSInteger. – mouviciel Feb 16 '09 at 20:53
  • I tested here with a minimal .m file and gcc and I get the same "case label does not reduce to an integer constant" for a "const int kAA=0;" constant (even with g++) – epatel Feb 16 '09 at 20:58
  • const int kTest = 0; int main() { int a = 1; switch (a) { case kTest: break; } } compiling as .m gives >> test1.m: In function ‘main’: test1.m:8: error: case label does not reduce to an integer constant – epatel Feb 16 '09 at 21:01
11

You can use

#define KNameIndex 0

...

switch (self.sectionFromParentTable) {
        case KNameIndex:
                self.types = self.facilityTypes;
                break;
        ...

and it should work.

Just had the same problem and I decided to go with #define rather than enum. Works for me™ ;-)

daniel
  • 645
  • 6
  • 8
0

This is a stab in the dark because I haven't used Cocoa / ObjC in a long time now, but is the member variable sectionFromParentTable not of int type?

Petriborg
  • 2,940
  • 3
  • 28
  • 49
0

I have not worked with Objective C, but I'd try chucking the 'extern'. At least if this were C++, the Constants.m file would not be part of the compilation unit of Other.m, so the value of KNameIndex would be unknown to the compiler. Which would explain the error; an unknowable value can't be a constant.

Does putting the definition, not just the declaration, in the Constants.h file help?

derobert
  • 49,731
  • 15
  • 94
  • 124
-1

I think you are stuck with using a const int instead of a const NSInteger as switch only works with built in integral types. (not sure about your syntax with const flipped around after the type).

Take a look at the related question: Objective-C switch using objects?

Community
  • 1
  • 1
crashmstr
  • 28,043
  • 9
  • 61
  • 79