可以使用 const 变量在 C 中声明数组的大小吗? [英] Can a const variable be used to declare the size of an array in C?
问题描述
为什么下面的代码会报错?
Why does the following code throw an error?
const int a = 5;
int b[a]={1,2,3,4,5};
而且当我尝试在没有const"关键字的情况下编译上面的代码时,我得到了同样的错误:
And also when I tried to compile the above code without "const" keyword, I got the same error:
int a = 5;
int b[a]={1,2,3,4,5};
为什么会这样?我在这里做的错误是什么?
why is it so? What is the mistake that I am doing here?
还有一个问题:什么时候用代码中的实际值替换常量,即如果我声明一个变量说:const int x= 5;我知道 RAM 中没有为变量 x 分配内存,但是 ROM 中的常量变量区域保存值 5,并且 x 在代码中出现的任何地方都被值 5 替换.但是什么时候会发生这种情况呢?编译时间?开机时间?预处理时间?
And also another question: When are constants replaced with their actual values in a code, i.e if I declare a variable say: const int x= 5; I know that no memory is allocated in RAM for the variable x, but constant variable area in ROM holds the value 5 and that x is simply replaced by the value 5 everywhere x appears in the code. But when does this happen? Compilation time? Boot up time? Preprocessing time?
PS:我说的是嵌入式 C(在微控制器等上运行),而不是在我的桌面上运行的 C.所以嵌入式系统必然要有ROM(Flash、EEPROM...).那会发生什么?
PS: I am talking about Embedded C (running on a Microcontroller etc), not C running on my desktop. So the embedded system is bound to have a ROM (Flash, EEPROM...). What would happen then?
推荐答案
这只是语言的限制.静态有界数组的大小需要是常量表达式,不幸的是,在 C 中,它只是类似于文字常量或 sizeof
表达式之类的东西,但是 不是 const
类型的变量.
It's simply a limitation of the language. The sizes of statically-bounded arrays need to be constant expressions, and unfortunately in C that's only something like a literal constant or a sizeof
expression or such like, but not a const
-typed variable.
(正如 Simon 指出的那样,从 C99 开始,还有 runtime-bounded 数组,或可变长度数组",其大小可以由任何变量的值给出.但这是一个不同的动物.)
(As Simon pointed out, since C99 there are also runtime-bounded arrays, or "variable-length arrays", whose size can be given by the value of any variable. But that's a different animal.)
你可能有兴趣听说 C++ 中的规则不同,其中 static const int
确实是一个常量表达式,C++11 甚至增加了一个新关键字,constexpr
,允许更广泛地使用常量表达式,这些表达式包含更多可以在编译时合理确定"的值.
You may be interested to hear that the rules are different in C++, where a static const int
is indeed a constant expression, and C++11 even adds a new keyword, constexpr
, to allow even more general use of constant expressions which encompass more things whose value "could reasonably be determined at compile time".
这篇关于可以使用 const 变量在 C 中声明数组的大小吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!