有没有 c/c++编译器可以警告(或给出错误)或枚举转换为 int?
清理使用硬编码整数文字而不是枚举的旧 C/C++ 代码时,找到已正确重构函数声明而不是主体的位置是很乏味的。例如,
enum important {
little = 1,
abit = 2,
much = 3
};
void blah(int e)
{
// magic stuff here
}
void boing(int e) { ... }
void guck(important e)
{
switch (e) {
case 3: // this would be a good place for a warning
blah(e); // and this
break;
default:
boing((int)e); // but this is OK (although imperfect and a warning would be acceptable)
break;
}
}
注释/修改每个枚举类型或搜索它们的代码也将是相当大量的工作,因为有非常非常多的不同枚举,因此这不是首选,但可能是一个可接受的解决方案。
我不需要它出现在我们的任何主要编译器或其他工具(主要是 gcc)或平台(大多数)中,手动运行几次就足够了,但我更喜欢一些不太深奥或不太昂贵的东西。
Cleaning up old c/c++ code that used hardcoded integer literals instead of enums, it is tedious to find places where the function-declaration has been properly refactored but not the body. e.g.
enum important {
little = 1,
abit = 2,
much = 3
};
void blah(int e)
{
// magic stuff here
}
void boing(int e) { ... }
void guck(important e)
{
switch (e) {
case 3: // this would be a good place for a warning
blah(e); // and this
break;
default:
boing((int)e); // but this is OK (although imperfect and a warning would be acceptable)
break;
}
}
Annotating/modifying each enum type or searching through the code for them would also be a fair amount of work as there are very very many different enums, so this is not preferred, but could be an acceptable solution.
I don't need it to be in any of our main compilers or other tools (gcc mostly) or platform (most), running it manually a couple of times would be enough, but I would prefer something that is not too esoteric or pricy.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
lint 将为您提供此警告(条件 641)
Splint (http://www.splint.org/download.html) 是一种现代 lint你可以使用
lint will provide this warning for you (condition 641)
Splint (http://www.splint.org/download.html) is a modern lint you can use
Sparse(Linux 内核人员使用的语义检查工具)可以帮助您与其中一些。
这些选项可以捕获枚举错误的子集:-Wenum-mismatch、-Wcast-truncate。然而,我通过这个运行了你的代码,看起来没有任何一个被捕获。
这是免费软件,如果您想扩展它。
Sparse (a semantic checker tool used by the linux kernel people) can help you with some of this.
A subset of enum errors can be caught by these options: -Wenum-mismatch, -Wcast-truncate. However, I ran your code through this and doesn't look like any of those were caught.
This is Free software, should you want to extend it.