Signedness of enum in C/C99/C++/C++x/GNU C/GNU C99

女生的网名这么多〃 提交于 2019-11-27 08:34:28

An enum is guaranteed to be represented by an integer, but the actual type (and its signedness) is implementation-dependent.

You can force an enumeration to be represented by a signed type by giving one of the enumerators a negative value:

enum SignedEnum { a = -1 };

In C++0x, the underlying type of an enumeration can be explicitly specified:

enum ShortEnum : short { a };

(C++0x also adds support for scoped enumerations)

For completeness, I'll add that in The C Programming Language, 2nd ed., enumerators are specified as having type int (p. 215). K&R is not the C standard, so that's not normative for ISO C compilers, but it does predate the ISO C standard, so it's at least interesting from a historical standpoint.

This is an old question... but I've just found out this:

typedef unsigned ENUMNAME;  // this makes it unsigned in MSVC C 2015
typedef enum {v0, v1, v2, v3} ENUMNAME;

You can use it as an 2-bit unsigned index, for example:

typedef struct {
  ENUMNAME i:2;
} STRUCTNAME;

Tried it in GCC ARM - doesn't work.
Also, WinDbg shows STRUCTNAME.i as a number, not as v0-v3.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!