C89:声明大型const数组,然后使用它,然后初始化它
这纯粹是为了可读性。我想拥有一个很大的恒定值,但这会使我的文件阅读愉快得多。因此,我想在使用后初始化该数组,尽管我希望它是恒定的。我知道这可能是不可能的,但这可能也很普遍。那么有哪些解决方法?我现在不想创建一个单独的文件。
像:
static const float array_of_values[1000];
float getValueFromArray(int index)
{
return array_of_values[index];
}
array_of_values = {0.123f, 0.456f, 0.789f ...};
This is purely for readability. I want to have a very large constant array of values, but it makes my file a lot less pleasant to read. So I'd like to have that array initialized after use, though I want it to be constant. I know this is probably impossible, but it's probably also very common. So what workarounds are there ? I do not want to create a separate file right now.
Some thing like :
static const float array_of_values[1000];
float getValueFromArray(int index)
{
return array_of_values[index];
}
array_of_values = {0.123f, 0.456f, 0.789f ...};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,您要做的不是初始化,而是简单的分配。而且您无法分配到数组。而且您不能在功能之外具有一般性语句。如果要初始化数组,则在定义数组时需要执行。
话虽如此,您必须记住(或了解)没有明确初始化的任何定义为 暂定 。
这意味着您可以创建一个初步的定义,基本上是为了使声明摆脱困境。然后,在源文件中的稍后位置,您可以添加实际定义:
First of all what you're doing is not initialization, it's plain assignment. And you can't assign to an array. And you can't have general statements outside of functions. If you want to initialize the array, you need to do it when defining the array.
With that said, you have to remember (or learn) that any definition without explicit initialization is tentative.
That means you can create a tentative definition, basically to get the declaration out of the way. Then at a later place in the source file you can add the actual definition:
这些是使文件不那么麻烦的常见解决方案:
或者
我个人会推荐宏观版本,因为它更灵活且不太神秘。您仍然可以在单独的标头文件中声明宏。
还有一些暂定的定义通常是一个坏主意,因为它使该代码变得神秘且难以阅读:
These are common solutions to make the file less cumbersome to read:
or
I would personally recommend the macro version since it's more flexible and less mysterious. You could still declare the macro in a separate header file.
There's also tentative definitions which is generally a bad idea, again because it makes the code mysterious and hard to read:
尝试以下操作:
Try this: