3

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.

darnir
  • 4,870
  • 4
  • 32
  • 47

1 Answers1

4

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.

Community
  • 1
  • 1
  • I went through as many questions as I could find on this topic on SO. However, my question is more about what is a better way to implement this, so that the value of ROWS is for all purposes a constant? – darnir Nov 23 '13 at 01:52
  • @darnir And what do you mean by `constant` then? That the value is known at compile-time rather than runtime? –  Nov 23 '13 at 01:54
  • Yes. Since all the values involved are indeed known at compile time, I thought it would be a good idea to have it computed at compile time itself. I realize that the performance gain is less than trivial, but right now, I'm both trying to shave off miliseconds and wanting to learn something new. – darnir Nov 23 '13 at 01:57
  • @darnir I don't think that's the same question you ask in the OP. The problem is ambiguity with the word `constant` as it means something different depending on the context you use it in. For all intents and purposes, it's a `compile-time constant`. Feel free to post it as a separate question, or ask squeamish to post the answer so you can accept it. –  Nov 23 '13 at 02:01