【发布时间】:2021-04-14 02:29:41
【问题描述】:
我正在 C 中寻找一种方法,在编译时检查是否设置了常量数组的所有元素。背景是,我想要一个带有命名行的查找表,它必须是完整的。
例子:
typedef enum [foo, bar, bla, max_value} rowNames;
static const uint32 LookupTable[max_value] =
{
[foo] = 123,
[bla] = 456, // oops, someone forgot to define the value for [bar]
}
retval = LookupTable[bar]; //this is to read out the value of the lookup table at a certain position
在此示例中,有人忘记定义数组元素 #1 [bar] 的值。我想确保在编译期间,所有值都已定义,错误会破坏构建。
当然,实际上表格会更大更复杂,但我认为这足以了解情况。尤其是后面要编辑枚举的时候,很有可能会出现枚举和表定义不一致的情况。
问候, 阿恩斯基
【问题讨论】:
-
一种方式:提供用于初始化或设置数组值的宏或函数。
-
好主意 kaylum,我可以尝试使用宏。只是担心,由于表的大小不是恒定的,使用可变参数宏创建枚举定义和表定义可能会变得复杂......
标签: arrays c compile-time