tags:

views:

3893

answers:

7

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?

A: 

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?

crashmstr
Note that NSInteger is defined as an int [typedef int NSInteger;] maybe you are thinking of NSNumber?
epatel
Ah, you are right. I'm still a long ways from being fluent in Objective-C.
crashmstr
A: 

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
A: 

Try using const NSInteger in place of NSInteger const.

mouviciel
+4  A: 

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
The const statement is perfectly legal in Objective-C, and perfectly operational with NSInteger.
mouviciel
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
<code>const int kTest = 0;int main() { int a = 1; switch (a) { case kTest: break; }}</code>compiling as .m gives >> test1.m: In function ‘main’:test1.m:8: error: case label does not reduce to an integer constant
epatel
+1  A: 

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
A: 

I tried both solutions given by epatel, and enum seems to be the way to go as none of the const routes worked.

enum {
    KNameIndex = 0,
    kAnotherConstant = 42
};
A: 
daniel