25: warning: initializer element is not a constant expression

c, constants, gcc

Solution

I believe your answer is here.

This will compile fine in C++, but not in C.

It has to do with C language. In C language objects with static storage duration has to be initialized with constant expressions or with aggregate initializers containing constant expressions.

A "large" object is never a constant expression in C, even if the object is declared as const.

Moreover, in C language the term "constant" refers to literal constants (like 1, 'a', 0xFF and so on) and enum members. Const-qualified objects (of any type) are not constants in C language terminology. They cannot be used in initializers of objects with static storage duration, regardless of their type.

Like squeamish says, `const int ROWS = 1 << MESH_K;` will work, but:

int test = 10;

const int ROWS = 1 << test;

Will NOT work. My guess is that `MESH_K` is pasted into the code as a literal, and therefore resolves to a C constant.

Problem

GCC gives me the following warning message when trying to compile: ``` las.c:13:18: warning: initializer element is not a constant expression [enabled by default] const int ROWS = pow (2, MESH_K); ``` The relevant code portions for this is: ``` #define MESH_K 10 #define BUFF_SIZE 30 const int ROWS = pow (2, MESH_K); ``` I need to use both MESH_K and ROWS at later points in the code. I understand that function calls are probably leading GCC to believe that this is not a constant expression. However given that this call to pow is essentially a constant, is there a better way to implement it (pre-processor macros perhaps?) and eliminate the warning? I don't mind sacrificing readability for performance in this part of the code, so any and all complex solutions are welcome.

Original source

Related problems