我有一个回调函数数组。仅当定义了“SOMETHING”时才应使用一个函数。在数组中包含 #ifdef 是否正确,例如:
void (*const array[])(void) =
{
function_callback1,
function_callback2,
function_callback3,
function_callback4,
#if defined ( SOMETHING)
function_callback5
#endif
};
该数组在头文件中定义为:
extern void (*const array[5])(void);
我违反了 MISRA 规定:
"Array has fewer initializers than its declared size. Default initialization is applied to the remainder of the array elements"
最佳答案
解决方案很简单,如果未定义 SOMETHING
,则使用 #else
和 NULL 指针:
#if defined ( SOMETHING)
function_callback5
#else
NULL
#endif
定义和声明都应该以相同的方式定义,使用大小常量:
void (*const array[5])(void) = {...
extern void (*const array[5])(void);
<小时/>
如果数组的大小也依赖于某些东西,则定义另一个宏:
#ifdef SOMETHING
#define ARRAY_SIZE 5
#else
#define ARRAY_SIZE 4
#endif
关于c - 在数组中使用#ifdef?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37541682/