Search code examples
cconstantsinitializer

Why do I get an error about the initializer not being a constant?


I am using the following code.

const int X_ORIGIN = 1233086;             
const int Y_ORIGIN = -4728071;              
const int Z_ORIGIN = 4085704;
const int xyzOrigin[NUM_DIMENSIONS] = {X_ORIGIN, Y_ORIGIN, Z_ORIGIN};

When I compile it, GCC gives me the following error.

Transformations.h:16:1: error: initializer element is not constant

What does that mean? How can I fix my code?


Solution

  • You can't do this at global scope in C, only at local scope, i.e. within a function:

    #define NUM_DIMENSIONS 3
    
    const int X_ORIGIN = 1233086;             
    const int Y_ORIGIN = -4728071;              
    const int Z_ORIGIN = 4085704;
    
    const int xyzOrigin[NUM_DIMENSIONS] = {X_ORIGIN, Y_ORIGIN, Z_ORIGIN}; // FAIL
    
    void foo(void)
    {
        const int xyzOrigin[NUM_DIMENSIONS] = {X_ORIGIN, Y_ORIGIN, Z_ORIGIN}; // OK
    }
    

    Alternatively you could compile the code as C++ rather than C.