Michael
Michael

Reputation: 9402

How can I get gcc to recognize an expression containing function calls as constant?

gcc does not like the following code:

inline const plus(unsigned x,unsigned y) __attribute__((pure));
inline const plus(unsigned x,unsigned y) { return x+y; }

int arr[plus(1,1)];

it throws the following error:

error: variably modified ‘arr’ at file scope

The only thing is, I have done everything I can think of to tell gcc that it can optimize a call to plus(a,b) to "a+b" and I have only passed constants, so the result should be constant!

Am I missing something to make this work? Or is gcc just not that smart?

By the way, the reason for using plus(1,1) instead of 1+1 is that it makes for more generic construction of the array size using macros.

Upvotes: 0

Views: 116

Answers (2)

Joachim Isaksson
Joachim Isaksson

Reputation: 180917

As far as I understand, the memory for arr[] is logically allocated even before main() is called and initialization of all static variables are guaranteed to be complete, and the compiler isn't (allowed to be) smart enough to figure out if the function you're referencing is safe to call before all statics are initialized.

In other words, the only way to do it is to (as Thomas does in his answer) use a #define macro which is evaluated at compile time to the constant 2.

Upvotes: 1

Thomas Padron-McCarthy
Thomas Padron-McCarthy

Reputation: 27632

There may be gcc extensions that allow something like this, but at least in standard C a function call is never counted as a constant expression, no matter how many const you add, or how constant it really is. You may have to use a macro instead:

#define plus(x, y) ((x)+(y))

Upvotes: 2

Related Questions