Search code examples
arrayscc89static-initialization

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

Solution

  • 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, /* ... */ };