开发者

Is there any c/c++ compiler that can warn (or give error) or enum conversion to int?

开发者 https://www.devze.com 2022-12-16 22:02 出处:网络
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.

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开发者_JAVA技巧 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.


lint will provide this warning for you (condition 641)

641 Converting enum to int -- An enumeration type was used in a context that required a computation such as an argument to an arithmetic operator or was compared with an integral argument. This warning will be suppressed if you use the integer model of enumeration (+fie) but you will lose some valuable type-checking in doing so. An intermediate policy is to simply turn off this warning. Assignment of int to enum will still be caught.

Splint (http://www.splint.org/download.html) is a modern lint you can use


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消