C 警告缺少默认初始化的查找表条目



考虑以下代码片段:

enum test {
A,
B,
C
};
static const char *const table[] = {
[A] = "A",
//[B] = "B",
[C] = "C",
}; // the string representation is not (always) equivalent to the enum identifier

如果我不小心错过了一个条目(在这种情况下B(,我想收到编译器警告或错误。

尝试使用clang -Weverything和多个gcc警告(但没有警告 - 静默编译(。

此外,sizeof table / sizeof *table仍然3.

或者 C 中有没有办法在编译时检查所有数组元素是否都是非 NULL?

// C++ variant
constexpr bool is_array_nonnull(const char *const array[]) {
for (int i = 0; i <= sizeof array / sizeof *array; ++i)
if (array[i] == nullptr)
return false;
return true;
}
static_assert(is_array_nonnull(table));

编辑:使要求和测试步骤更加清晰

为了防止这种情况,您可以使用一种称为X 宏的技术。

#define TESTLIST  X(A), X(B), X(C)
#define X(item) item
enum test { TESTLIST };
#undef X
#define X(item) [item] = #item
static const char *const table[] = { TESTLIST };
#undef X

扩展到

enum test { A, B, C };
static const char *const table[] = { [A] = "A", [B] = "B", [C] = "C" };

在列表中添加或删除项目时,只需修改TESTLIST宏。代码的其余部分保持不变。

目前,我正在使用"单元测试",它使用运行时函数检查查找表的每个字段是否已正确初始化(非空(。

最新更新