为什么以下代码会抛出错误?
const int a = 5;
int b[a]={1,2,3,4,5};
Run Code Online (Sandbox Code Playgroud)
而且当我尝试编译没有"const"关键字的上述代码时,我得到了同样的错误:
int a = 5;
int b[a]={1,2,3,4,5};
Run Code Online (Sandbox Code Playgroud)
为什么会这样?我在这里做的错误是什么?
还有另一个问题:什么时候常量被代码中的实际值替换,即如果我声明一个变量说:const int x = 5; 我知道在RAM中没有为变量x分配内存,但是ROM中的常量变量区域保持值5,并且x在代码中出现x的地方简单地替换为值5.但这什么时候发生的?编译时间?启动时间?预处理时间?
PS:我说的是嵌入式C(在微控制器上运行等),而不是在桌面上运行的C. 因此嵌入式系统必然会有一个ROM(Flash,EEPROM ......).那会发生什么?
I am perfectly aware of the mechanism behind the switch statement and why an integer constant is required. What I don't undestand is why the following case label is not considered an integer constant. What is it then? A non-existing variable? Can anyone categorize it? Does the C compiler really need to be so dumb?
struct my_struct {
const int my_int;
};
switch (4) {
case ((struct my_struct) { 4 }).my_int:
printf("Hey there!\n");
break;
}
Run Code Online (Sandbox Code Playgroud)
And of course…
error: case …Run Code Online (Sandbox Code Playgroud)