在 C89 中通过查找表进行可移植的用户定义字符类划分,你会这样做吗?
static const int class[UCHAR_MAX] =
{ [(unsigned char)'a'] = LOWER, /*macro value classifying the characters*/
[(unsigned char)'b'] = LOWER,
.
.
.
}
这只是一个想法。这是一件坏事吗?
static const int class[UCHAR_MAX] =
{ [(unsigned char)'a'] = LOWER, /*macro value classifying the characters*/
[(unsigned char)'b'] = LOWER,
.
.
.
}
This is just an idea. Is it a bad one?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
指定初始化器位于 C99 中,而不是 C89 中。它们也作为 C89 的 GCC 扩展存在,但不可移植。
除此之外,使用查找表是快速处理少量对象分类的常用方法。
编辑:但有一个更正:数组的大小应该是
UCHAR_MAX+1
Designated initializers are in C99, not C89. They also exist as a GCC extension for C89, but will not be portable.
Other than that, the use of lookup tables is a common way to handle classification of a small number of objects quickly.
Edit: One correction though: The size of the array should be
UCHAR_MAX+1
顺便说一句,GCC 的指定初始化器扩展允许
初始化器应用于索引范围,后面的初始化会覆盖前面的初始化。
但非常不标准;这不在 C89/C90 或 C99 中。
BTW, GCC's designated initializer extensions allow for
initializers applying to ranges of indices, with later initializations overriding earlier ones.
Very non-standard, though; this isn't in C89/C90 nor C99.
不幸的是,这在 C89/90 中不可移植。
Unfortunately, that is not portable in C89/90.
除了使用
int
而不是unsigned char
作为类型(从而浪费 768 字节)之外,我认为这是一个非常好的想法/实现。请记住,它依赖于 C99 功能,因此它不适用于旧的 C89/C90 编译器。另一方面,简单的条件语句应该具有相同的速度并且代码大小要小得多,但它们只能有效地表示某些自然类。
ETC。
Aside from using
int
rather thanunsigned char
for the type (and thereby wasting 768 bytes), I consider this a very good idea/implementation. Keep in mind that it depends on C99 features, so it won't work with old C89/C90 compilers.On the other hand, simple conditionals should be the same speed and much smaller in code size, but they can only represent certain natural classes efficiently.
etc.