可一个const变量用来声明C中的数组的大小? [英] Can a const variable be used to declare the size of an array in C?

查看:219
本文介绍了可一个const变量用来声明C中的数组的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以下code抛出一个错误?

Why does the following code throw an error?

const int a = 5;
int b[a]={1,2,3,4,5};

和也,当我试图编译上面的code没有常量关键字,我得到了同样的错误:

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?

和另一种问题:
当常数与它们的实际值替换在code,即如果我声明一个变量说:const int的X = 5;
我知道,没有内存分配在RAM中的变量x,但在ROM常变量区域存放值5和x被简单地由5处处x会出现在code中的值替换。但是,当出现这种情况?编译时间?开机时间? preprocessing时间?

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(闪存,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?

推荐答案

它只是语言的限制。静态界数组的大小必须的恒前pressions 的,不幸的是在C,它只是像一个常量或的sizeof 前pression或诸如此类,但的的一个常量 -typed变量。

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.

(西蒙指出,由于C99还有的运行时有界的阵列,或变长数组,其大小可以通过任何变量的值给出。但是这是一个不同动物。)

(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 ++中,其中静态const int的的确是一个恒定的前pression是不同的,C ++ 11即使增加了一个新的关键字, constexpr ,让更多的一般使用恒定的前pressions其中包括更多的东西,其价值可以合理地在编译时确定的。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆