C 常量引发编译时错误
有几个人在这里评论了我的 C 代码,说我应该使用常量作为循环计数器,而不是硬写它们。我同意他们的观点,因为这是我编写 Java 代码时的做法,但是当我尝试在数组声明和循环条件中使用常量时,我会抛出编译时错误。
要在 C 中声明常量,语法为#define NAME value
。
在我的代码中,我有两个常量,BUFFER
是文件读取缓冲区,PACKED
是输出数组大小。
我使用 BUFFER
将 char inputBuffer[BUFFER]; 初始化为全局变量,这有效,但是当我尝试使用 PACKED
时,
#define PACKED 7; // this line is in the header of file, just below preprocessors
int packedCount;
char inputPack[PACKED]; //compression storage
for (packedCount=0; packedCount<= PACKED; packedCount++){
我得到了错误:“;”之前应有“]”
ANDchar inputPack[PACKED]
处的令牌错误:“;”之前有预期的表达式token
在循环初始化行中。当我将 PACKED
替换为 7 时,这两个错误都消失了。
Several people have commented on my C code here, saying that I should use constants as loop counters, rather than hard-writing them. I agree with them, since that is my practice when writing Java code, but I'm having compile-time errors thrown when I try to use constants in array declarations and loop conditionals.
To declare a constant in C, the syntax is #define NAME value
.
In my code, I have two constants,BUFFER
is the file read buffer, and PACKED
is the output array size.
I use BUFFER
to initialize char inputBuffer[BUFFER];
as a global variable, which works, but when I try to use PACKED
#define PACKED 7; // this line is in the header of file, just below preprocessors
int packedCount;
char inputPack[PACKED]; //compression storage
for (packedCount=0; packedCount<= PACKED; packedCount++){
I get am error: expected ‘]’ before ‘;’ token
at char inputPack[PACKED]
ANDerror: expected expression before ‘;’ token
in the loop initialization line. Both errors disappear when I replace PACKED
with 7.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
显然,您发布的代码与源文件中显示的代码并不完全相同。
至少,您在 char inputPack[PACKED] 后面缺少分号。
我强烈怀疑您的真实来源在宏声明末尾有一个分号,这会导致错误。宏定义不应以分号终止。
You obviously are not posting the code exactly as it appears in your source file.
At the very least, you are missing the semicolon after
char inputPack[PACKED]
.I strongly suspect that your real source has a semicolon at the end of your macro declaration, which would cause the error. Macro definitions should not be terminated with a semicolon.
char
inputPack[PACKED]
之后缺少一个;
there is a
;
missing after charinputPack[PACKED]
尝试使用 PACKED 以外的其他内容,例如 PACKEDSIZE。 可能是您的编译器将 PACKED 用于其他用途(例如与结构打包相关)。另外,正如其他答案提到的,您缺少 ;
Try using something other than PACKED, e.g. PACKEDSIZE. It could be that your compiler uses PACKED for something else (e.g. related to struct packing). Also, as other answers mention, you're lacking a ;