0

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.

1
  • Your plus has no return type. Also, you need a constant expression, which the result of a function call is not. (In C++11 you can do something else that'll make it work.) Commented Mar 6, 2012 at 22:55

2 Answers 2

2

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))
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.