-
-
Save mikeash/1132620 to your computer and use it in GitHub Desktop.
#import <Foundation/Foundation.h> | |
// .h file | |
struct MyConstantsStruct | |
{ | |
NSString *foo; | |
NSString *bar; | |
int baz; | |
}; | |
extern const struct MyConstantsStruct MyConstants; | |
// .m file | |
const struct MyConstantsStruct MyConstants = { | |
.foo = @"foo", | |
.bar = @"bar", | |
.baz = 42 | |
}; | |
// user | |
int main(int argc, char **argv) | |
{ | |
[NSAutoreleasePool new]; | |
NSLog(@"%@ %@ %d", MyConstants.foo, MyConstants.bar, MyConstants.baz); | |
} |
That is true, however the same is true of a simple global variable constant, nothing to do with the struct. The only way to avoid this would be to use #define
or enum
instead of a "real" global variable constant.
I guess I assumed 'dynamic arrays' in c99 would let me use them in structs. What's the enum idea? Thanks.
Variable length arrays are only available for local variables. Otherwise the compiler needs to know sizes at compile time.
Enum constants look like this:
enum
{
kMyConstant = 42,
kMyOtherConstant = 99
};
Of course, since enums can only be integers, this construct can only be used for integer constants.
Oh cool, I didn't know they could be assigned values. Thanks Mike, good tip. :)
ARC does not allow it... :(
ARC does allow it, but unfortunately you must put __unsafe_unretained
before all of the object pointer struct members to make ARC happy.
I like the idea, but it sort of falls down when you try to use one of them as a field size within the same header e.g.:
fractalworld.h:
char username[fractalworld_constants.username_len];
clang says: fields must have a constant size: 'variable length array in structure' extension will never be supported
Am I missing something obvious or is this just unfortunate?