ISO C90 forbids variable length array

泪湿孤枕 提交于 2019-11-28 09:31:52

const-qualifying a variable doesn't make it a compile-time constant (see C99 6.6 §6 for the defintion of an integer constant expression), and before the introduction of variable-length arrays with C99, array sizes needed to be compile-time constants.

It's rather obvious that const-qualify a variable doesn't make it a compile-time constant, in particular in case of function parameters which won't be initialized until the function is called.

I see the following solutions to your problem:

  • compile your code as C99 via -std=c99 or -std=gnu99
  • allocate your buffer via malloc()
  • use alloca() if available, which is the closest you can come to variable-length arrays with C90
  • choose a maximum buffer size which is always used and fail if the given limit argument overflows

As a side note, even though C99 allows variable-length arrays, it's still illegal to use the value of an integer variable with static storage duration as size for an array with static storage duration, regardless of const-qualification: While there's nothing which prevents this in principle if the integer variable is initialized in the same translation unit, you'd have to special-case variables with visible defintion from those whose definition resides in a different translation unit and would either have to disallow tentative defintions or require multiple compilation passes as the initialization value of a tentatively defined variable isn't known until the whole translation unit has been parsed.

const does not introduce a constant in C but a read-only variable.

#define SIZE 16
char bla[SIZE];   // not a variable length array, SIZE is a constant

but

const int size 16;
char bla[size];   // C99 variable length array, size is not constant

c90 doesn't allow variavble length arrays. However, you can use c99 gcc ompiler to make this work.

You are compiling with c90 gcc but looking at c99 spec :)

No it is not a bug. You can't use a VLA in C90. When you declared

const size_t limit

that is not a constant expression. A constant expression would be something like a literal value 666.

Note that C differs significantly from C++ in this regard. Even a constant like this

const int i = 666;

is not a constant expression in C. This is the primary reason why constant values are typically declared with #define in C.

As written in your question, this is from C99, not C90, you need to compile it against C99 to be able to use variable length arrays.

A const qualified variable is not an integer constant expression in the sense of the standard. This has to be a literal constant, an enumeration constant, sizeof or some expression composed with these.

Switch to C99 if you may. The gcc option is -std=c99 (or gnu99 if you want gnu extension.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!