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 1 It's not inside a function, which means it has to be an initializer - which is assigned only when the item is declared - which means it must be a constant value at compile time, which malloc cannot be.
Moreover, in C language, the term "constant" refers to literal constants (like 1 , 'a' , 0xFF and so on), enum members, and results of such operators as sizeof . Const-qualified objects (of any type) are not constants in C language terminology.
Often people are mislead by the naming of the keyword const
, implying something of a constant value that can't be changed. In C at least, it means readonly. const
qualified objects at file scope are not having the proper constness to serve as array initializers.
As an example for non-constant constness, it is perfectly ok to declare
const volatile unsigned int milliseconds_since_boot;
being a value that gets updated from outside the compiler's control (think HW register) and that you are not allowed to assign to, i.e. it is readonly.
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.
I'm not a proper programmer ;) but I'd do this:
#define X_ORIGIN (1233086)
#define Y_ORIGIN (-4728071)
#define Z_ORIGIN (4085704)
const int xyzOrigin[NUM_DIMENSIONS] = {X_ORIGIN, Y_ORIGIN, Z_ORIGIN};
That way it's just a text-substitution. If the compiler still spits the dummy at least you're a step closer to knowing where the issue is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With