我们可以在结构声明中使用#define常量作为数组大小吗?
我正在 C 中执行以下操作
#define MAX_DATA_SIZE 500;
struct reliable_state {
char dataBuffer[MAX_DATA_SIZE];
}
,即我想在结构声明中使用 #define 常量作为数组大小。 但上面的代码给出了奇怪的错误
.c:36: error: expected ‘]’ before ‘;’ token
那么还有其他方法可以做到这一点吗?
I am doing the following in C
#define MAX_DATA_SIZE 500;
struct reliable_state {
char dataBuffer[MAX_DATA_SIZE];
}
i.e I want to use the #define constant as array size in structure declaration.
But above code gives weird error
.c:36: error: expected ‘]’ before ‘;’ token
So is there any other way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,你可以,只需删除“;”在你的定义行中:
使用定义,编译器实际上会“看到”你的结构定义,因为
这显然是错误的。
Yes you can, just remove ';' in your define line:
With define you have compiler will actually 'see' your struct definition as
which is clearly erroneous.
当您使用
#define
时,右侧的宏将“按原样”定义。例如,在这里,您只需将其更正为When you use
#define
, the macro on the right side is defined "as is". E.g. here, you've just have to correct it to非空类对象宏定义的语法为
请注意,与 C 声明和语句不同,此语法中没有终止分号。您的分号成为替换的一部分,并插入到您使用宏标识符的位置,产生
编译器诊断的语法错误。
The syntax for a non-empty object-like macro definitions is
Note that there is no terminating semicolon in this syntax, unlike for C declarations and statements. Your semicolon became part of the REPLACEMENT and was inserted where you used the macro identifier, yielding
which is a syntax error the compiler diagnosed.