在文件范围内可变修改的数组

我希望创建一个常量静态数组,以便在 Objective-C 实现文件中使用,类似于在我的“顶层”中使用的类似内容。M 」档案:

static const int NUM_TYPES = 4;
static int types[NUM_TYPES] = {
1,
2,
3,
4 };

我计划稍后在文件中使用 NUM_TYPES,所以我想把它放在一个变量中。

但是,当我这样做的时候,我得到了错误

“在文件范围内可变修改的‘ type’”

我认为这可能与数组大小是一个变量有关(当我在那里放入一个整数文字时,如 static int types[4],我不会得到这个消息)。

我想解决这个问题,但也许我的方法完全错了... ... 我有两个目标:

  1. 具有可在整个文件中访问的数组
  2. NUM_TYPES封装成一个变量,这样我的文件中就不会有相同的文本散布在不同的地方

有什么建议吗?

[编辑] 在 C 常见问题中发现了这个 http://c-Faq.com/ansi/constasconst.html :

121900 次浏览
#define NUM_TYPES 4

If you're going to use the preprocessor anyway, as per the other answers, then you can make the compiler determine the value of NUM_TYPES automagically:

#define NUM_TYPES (sizeof types / sizeof types[0])
static int types[] = {
1,
2,
3,
4 };

It is also possible to use enumeration.

typedef enum {
typeNo1 = 1,
typeNo2,
typeNo3,
typeNo4,
NumOfTypes = typeNo4
}  TypeOfSomething;

The reason for this warning is that const in c doesn't mean constant. It means "read only". So the value is stored at a memory address and could potentially be changed by machine code.

Imho this is a flaw in many c compilers. I know for a fact that the compilers i worked with do not store a "static const"variable at an adress but replace the use in the code by the very constant. This can be verified as you will get the same checksum for the produced code when you use a preprocessors #define directive and when you use a static const variable.

Either way you should use static const variables instead of #defines whenever possible as the static const is type safe.

As it is already explained in other answers, const in C merely means that a variable is read-only. It is still a run-time value. However, you can use an enum as a real constant in C:

enum { NUM_TYPES = 4 };
static int types[NUM_TYPES] = {
1, 2, 3, 4
};