static const int class[UCHAR_MAX] =
{ [(unsigned char)'a'] = LOWER, /*macro value classifying the characters*/
[(unsigned char)'b'] = LOWER,
.
.
.
}
这只是一个想法。这是一个坏的吗?
指定的初始化器在 C99 中,而不是 C89。它们也作为 C89 的 GCC 扩展存在,但不可移植。
除此之外,使用查找表是快速处理少量对象分类的常用方法。
编辑:虽然一个更正:数组的大小应该是UCHAR_MAX+1
顺便说一句,GCC 的指定初始化扩展允许
static const int class[] = {
[0 ... UCHAR_MAX] = UNCLASSIFIED,
[(unsigned)'0' ... (unsigned)'9'] = DIGIT,
[(unsigned)'A' ... (unsigned)'Z'] = UPPER,
[(unsigned)'a' ... (unsigned)'z'] = LOWER,
};
初始化器应用于索引范围,后面的初始化覆盖早期的初始化。
但是,非常不标准;这不在 C89/C90 和 C99 中。
不幸的是,这在 C89/90 中是不可移植的。
$ gcc -std=c89 -pedantic test.c -o test
test.c:4: warning: ISO C90 forbids specifying subobject to initialize
test.c:5: warning: ISO C90 forbids specifying subobject to initialize
除了使用int
而不是unsigned char
类型(从而浪费 768 个字节)之外,我认为这是一个非常好的想法/实现。请记住,它依赖于 C99 特性,因此它不适用于旧的 C89/C90 编译器。
另一方面,简单的条件应该具有相同的速度并且代码量要小得多,但它们只能有效地表示某些自然类。
#define is_ascii_letter(x) (((unsigned)(x)|32)-97<26)
#define is_digit(x) ((unsigned)(x)-'0'<10)
等等