static const int size = 5;
@interface Foo { char bar[size]; }
But the compiler complains that “instance variables must have constant size”. Do I really开发者_Go百科 have to #define
the size, or is there a way to get it work with a regular constant? (I’d like the memory to be allocated statically, no malloc
.)
It is likely that your Objective-C compiler uses a C compiler as a backend. C (up to C98) only permits constant expressions as array sizes. This is what your compiler is complaining about. So you don't get to use an identifier as an array size. (In short, if the preprocessor can't compute the number, it's not going to work.) So, yes, you're going to get to use a #define.
Note to readers like me: remember to put parens around anything in a #define beyond a simple numerical value.
#define SMALL_ONE 10
#define BIG_ONE SMALL_ONE + 10 /* can cause problems */
#define BETTER_BIG (SMALL_ONE + 10) /* recommended */
The problem arises because #define is handled by the preprocessor, which does essentially a string substitution. (If you do web search for 'putting parens around a #define constant' or similar I'm sure you'll find examples and style guides that show explanatory examples.)
精彩评论