为什么这个 C 程序不能编译?这有什么问题吗?
我已经在 wxDevC++
和 Turbo C++ 3.0 上试过了。
主.c
#include<stdio.h>
#include<conio.h>
const int SIZE = 5;
int main(int argc, char ** argv)
{
char array[SIZE] = {'A', 'B', 'C', 'D', 'E'};
printf("Array elements are,\n");
int i=0;
for(i=0 ; i<SIZE ; ++i)
{
printf("%c ", array[i]);
}
getch();
return 0;
}
两个编译器的错误信息是相似的。
f:\_Source-Codes\main.c In function `main':
8 f:\_Source-Codes\main.c variable-sized object may not be initialized
最佳答案
C89/90 语言中的数组大小必须由整数常量表达式 指定(通常对于 C99 也是如此)。 C 中的 const int
对象不是常量表达式,这就是为什么不能使用它来指定数组大小的原因。注意:这是 C 和 C++ 之间的一个显着区别。
在 C 语言中,术语常量 是指文字 常量,即5
、10.2
、 0xFF
、'a'
等等(准确地说,枚举常量也是常量)。 const int
对象不是 C 中的常量,不能用于构建常量表达式。
如果你想在 C 中预先声明一个命名常量用作数组大小,你必须使用 #define
或 enum
。这同样适用于 case 标签、位域大小和所有其他需要常量表达式的上下文。
参见 this了解更多详情。
关于c - 为什么这个 C 程序不能编译?这有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3167351/