在文件范围内可变修改的数组
我想创建一个在整个 Objective-C 实现文件中使用的常量静态数组,类似于我的“.m”文件顶层的类似内容:
static const int NUM_TYPES = 4;
static int types[NUM_TYPES] = {
1,
2,
3,
4 };
我计划稍后使用 NUM_TYPES
在文件中,所以我想把它放在一个变量中。
但是,当我这样做时,我收到错误
“在文件范围内可变地修改‘类型’”
我认为这可能与作为变量的数组大小有关(当我在那里放置整数文字时,我没有收到此消息,例如 static int types[ 4]
)。
我想解决这个问题,但也许我的做法是错误的...我这里有两个目标:
- 拥有一个可在整个文件中访问的数组
- 将
NUM_TYPES
封装到变量中,所以我我的文件中的不同位置没有相同的文字
我该怎么办?
我在 C FAQ (11.8) 中找到了这个: 我不明白为什么我可以不在初始值设定项和数组维度中使用 const 值
I want to create a constant static array to be used throughout my Objective-C implementation file, similar to something like this at the top level of my ".m" file:
static const int NUM_TYPES = 4;
static int types[NUM_TYPES] = {
1,
2,
3,
4 };
I plan on using NUM_TYPES
later on in the file, so I wanted to put it in a variable.
However, when I do this, I get the error
"Variably modified 'types' at file scope"
I gather that this may have something to do with the array size being a variable (I don't get this message when I put an integer literal there, like static int types[4]
).
I want to fix this, but maybe I am going about it all wrong...I have two goals here:
- To have an array which is accessible throughout the file
- To encapsulate
NUM_TYPES
into a variable, so I don't have the same literal scattered about different places in my file
What can I do?
I found this in the C FAQ (11.8): I don't understand why I can't use const values in initializers and array dimensions
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
此警告的原因是 C 中的'const' 并不意味着常量。它的意思是“只读”。因此该值存储在内存地址中,并且可能会被机器代码更改。
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.
如果您无论如何都要使用预处理器,按照其他答案,那么您可以让编译器自动确定
NUM_TYPES
的值: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:也可以使用枚举。
It is also possible to use enumeration.
正如其他答案中已经解释的那样,C 中的 const 仅意味着变量是只读的。它仍然是一个运行时值。但是,您可以使用
enum
作为 C 中的实常量: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 anenum
as a real constant in C:恕我直言,这是许多 C 编译器的缺陷。我知道我使用的编译器不会在地址处存储“静态常量”变量,而是用常量替换代码中的使用。这可以得到验证,因为当您使用预处理器 #define 指令和使用静态 const 变量时,生成的代码将获得相同的校验和。
无论哪种方式,您都应该尽可能使用 static const 变量而不是 #defines,因为 static const 是类型安全的。
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 address, 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.