View Full Version : constants inside switch
MrFusion
Sep 18, 2007, 12:49 PM
I thought to be smart and define a sets of constants, just like Apple.
e.g. NSTableViewNoColumnAutoresizing
.h file:
extern int const myConstant;
.m file:
int const myConstant = 9;
So I figured I could use these in a switch
swith ([delegate mySwitch]) {
case myConstant:
break;
}
But this gives a compile error. Is this normal and I can not do things in this manner, or did I do something wrong?
error: case label does not reduce to integer constant
gnasher729
Sep 18, 2007, 01:43 PM
I thought to be smart and define a sets of constants, just like Apple.
e.g. NSTableViewNoColumnAutoresizing
.h file:
extern int const myConstant;
.m file:
int const myConstant = 9;
So I figured I could use these in a switch
swith ([delegate mySwitch]) {
case myConstant:
break;
}
But this gives a compile error. Is this normal and I can not do things in this manner, or did I do something wrong?
error: case label does not reduce to integer constant
It's normal. You are using Objective-C, which is based on C, not on C++. In the C language, const variables are still variables and don't count as "constant expressions".
Usually your best choice is to use an "enum" to define a number of related constants; slightly less good is to use a series of #define preprocessor statements.
lazydog
Sep 18, 2007, 05:28 PM
.h file:
extern int const myConstant;
.m file:
int const myConstant = 9;
I don't think this would work even in C++ in general anyway. It works if the .m file containing the switch can see the value of myConstant but if it only sees the .h file, ie myConstant really is an extern, then the compiler would throw a similar error. I think you're much better off using enums or #defines like gnasher729 suggests.
b e n
vBulletin® v3.8.6, Copyright ©2000-2012, Jelsoft Enterprises Ltd.