检测不匹配的阵列<->枚举初始值设定项 [英] Detecting mismatched array <-> enum initializers

查看:42
本文介绍了检测不匹配的阵列<->枚举初始值设定项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 C 进行嵌入式编程时,很多时候我发现自己使用枚举和数组进行映射,因为它们速度快且内存效率高.

When doing embedded programming with C, many times I find myself doing maps with enum and array because they are fast and memory efficient.

enum {
    ID_DOG = 0,
    ID_SPIDER,
    ID_WORM,
    ID_COUNT
};
int const NumberOfEyes[ID_COUNT] = {
    2,
    8,
    0
};

问题是有时在添加/删除项目时,我会出错并且枚举和数组不同步.如果初始化列表太长,编译器会检测到它,但不会检测到.

Problem is that sometimes when adding/removing items, I make mistake and enum and array go out of sync. If initializer list is too long, compiler will detect it, but not other way around.

那么是否有可靠且可移植的编译时检查初始化列表是否与数组长度匹配?

So is there reliable and portable compile time check that initializer list matches the length of the array?

推荐答案

像下面这样的编译时断言怎么样?(是的,还有更详细的 CT_ASSERT 宏;这是为了说明这个想法.)

What about a compile time assertion like the following? (Yes, there are more elaborate CT_ASSERT macros; this is to illustrate the idea.)

#define CT_ASSERT(expr, name) typedef char name[(expr)?1:-1]

enum {
    ID_DOG = 0,
    ID_SPIDER,
    ID_WORM,
    ID_COUNT
};

int const NumberOfEyes[] = {
    2,
    8,
    0
};

CT_ASSERT (sizeof NumberOfEyes/sizeof *NumberOfEyes == ID_COUNT, foo);

现在当 NumberOfEyes 数组的元素多于或少于 ID_COUNT 时,这将导致沿 xc:15: error: size of array 'foo> 出现错误' 是否定的.负数组维数是违反约束的,任何 C 编译器都必须对其进行诊断.

Now when the NumberOfEyes array has more or less elements than ID_COUNT, this will cause an error along x.c:15: error: size of array 'foo' is negative. Negative array dimensions are a constraint violation that must be diagnosed by any C compiler out there.

这篇关于检测不匹配的阵列<->枚举初始值设定项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆