简体   繁体   中英

C89: declare large const array, then use it, then initialize it

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 ...};

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:

static const float array_of_values[1000];

float getValueFromArray(int index)
{
    return array_of_values[index];
}

static const float array_of_values[] = { 0.123f, 0.456f, 0.789f, /* ... */ };

These are common solutions to make the file less cumbersome to read:

static const float array_of_values[1000] = { MACRO }; // macro being an initalizer list

or

static const float array_of_values[1000] = 
{ 
  #include "initlist.h"
};

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:

static const float array_of_values[1000];

float getValueFromArray(int index)
{
    return array_of_values[index];
}

static const float array_of_values[1000] = {0.123f, 0.456f, 0.789f};

#include <stdio.h>

int main (void)
{
  printf("%f\n", array_of_values[0]);
  printf("%f\n", getValueFromArray(0));
}

Try this:

#include <stdio.h>

static float array_of_values_base[1000]; // the effective array has "base" in its identifier
static const float *array_of_values = array_of_values_base; // your array is now a pointer

float getValueFromArray(int index)
{
    return array_of_values[index];
}

int main(void) {
    array_of_values_base[0] = 0.123f;
    array_of_values_base[1] = 0.456f;
    array_of_values_base[2] = 0.789f;
    // ...
    printf("value at index 1 is %f\n", getValueFromArray(1));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM