Skip to content

Instantly share code, notes, and snippets.

@mikeash
Created August 8, 2011 20:17
Show Gist options
  • Save mikeash/1132620 to your computer and use it in GitHub Desktop.
Save mikeash/1132620 to your computer and use it in GitHub Desktop.
Namespaced constants in C
#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);
}
@mikeash
Copy link
Author

mikeash commented Aug 8, 2011

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.

@dsturnbull
Copy link

Oh cool, I didn't know they could be assigned values. Thanks Mike, good tip. :)

@uchuugaka
Copy link

ARC does not allow it... :(

@mikeash
Copy link
Author

mikeash commented Jan 30, 2012

ARC does allow it, but unfortunately you must put __unsafe_unretained before all of the object pointer struct members to make ARC happy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment