我想定义一个数组,宏的长度如下,
#define A (2.5)
#define B (2.0)
#define LEN (A*B) // I know LEN is an integer, not decimal numbers
static int array[LEN] // define an integer array, length is A*B=5
我有一个编译检查来保证 LEN 是一个整数,
就像 build_assert( (int)LEN == LEN )
编译器给出“数组'array'的大小具有非整数类型”,更改它的最佳方法是什么?
这个方法应该有效:
#define A (2.5)
#define B (2.0)
/* If you want to round,define it like this:
#define LEN(x) ((size_t)(x+0.5))
If you sure LEN has two arguments and you
don't care it may result in allocating a
little more space, define it like this:
#define LEN(a, b) (((size_t)(a)+1)*((size_t)(b)+1)))
*/
#define LEN(x) ((size_t)(x))
static int array[LEN(A*B)];