问题描述
enum
类型是有符号的还是无符号的?枚举的符号性是否不同:C/C99/ANSI C/C++/C++x/GNU C/GNU C99?
Is the enum
type signed or unsigned? Does the signedness of enums differ between: C/C99/ANSI C/C++/C++x/GNU C/ GNU C99?
谢谢
推荐答案
枚举保证由整数表示,但实际类型(及其符号)取决于实现.
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 };
在 C++0x 中,可以显式指定枚举的基础类型:
In C++0x, the underlying type of an enumeration can be explicitly specified:
enum ShortEnum : short { a };
(C++0x 还增加了对作用域枚举的支持)
(C++0x also adds support for scoped enumerations)
为了完整起见,我将在 The C Programming Language, 2nd ed. 中添加,枚举器被指定为具有 int
类型(第 215 页).K&R 不是 C 标准,所以它不是 ISO C 编译器的规范,但它确实早于 ISO C 标准,所以它至少从历史的角度来看很有趣.
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.
这篇关于C/C99/C++/C++x/GNU C/GNU C99 中枚举的签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!