views:

39

answers:

1

Hello! I’d like to do this:

static const int size = 5;
@interface Foo { char bar[size]; }

But the compiler complains that “instance variables must have constant size”. Do I really 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.)

+2  A: 

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.

Eric Towers
See <a href="http://en.wikipedia.org/wiki/C%2B%2B0x#Generalized_constant_expressions">C++0x, Generalized constant expressions</a> for a similar problem in C++.
Eric Towers
I’m using LLVM 1.5 and have the choice between ANSI C, C89, GNU89, C99 and GNU99 language dialects. Does that change anything?
zoul
@zoul: not really. By the way, #define is not the enemy. It's just as good as const int blah-blah-blah. The kind of #define that is the enemy involves necessarily nested macros, uses of # and ## in innovative ways, and macro functions with unexpected (numbers of) side effects. #define-ing consts is not something to shun.
Eric Towers
You’re right. I don’t like defines anyway, simply since they are not first class citizens (no refactoring for example), but this case certainly does not hurt.
zoul