Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 283
CodeKingPlusPlus Avatar asked Jul 18 '12 12:07

CodeKingPlusPlus


People also ask

What is the error initializer element is not constant?

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.

What is not constant in C?

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.


3 Answers

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.

like image 90
Jens Avatar answered Sep 20 '22 15:09

Jens


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.

like image 33
Paul R Avatar answered Sep 17 '22 15:09

Paul R


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.

like image 43
John U Avatar answered Sep 21 '22 15:09

John U