开发者

can we use #define constant in struct declaration as array size?

开发者 https://www.devze.com 2023-04-12 22:51 出处:网络
I am doing the following in C #define MAX_DATA_开发者_如何学运维SIZE 500; struct reliable_state {

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?


Yes you can, just remove ';' in your define line:

#define MAX_DATA_SIZE 500

With define you have compiler will actually 'see' your struct definition as

char dataBuffer[500;];

which is clearly erroneous.


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

#define MAX_DATA_SIZE 500  /* no semicolon */


The syntax for a non-empty object-like macro definitions is

#define MACRO_IDENTIFIER    REPLACEMENT

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

char dataBuffer[500;];

which is a syntax error the compiler diagnosed.

0

精彩评论

暂无评论...
验证码 换一张
取 消