开发者

Enumerated Type Width?

Quick question. How wide are enumerated types? Are they of the minimum width required to represent the enumeration or are all enums ints? If they're ints, can yo开发者_JS百科u change the width of enums or would you have to type cast for each occurrence?


(This is for C++)

From the standard:

The underlying type of an enumeration is an integral type that can represent all the enumerator values defined in the enumeration. It is implementation-defined which integral type is used as the underlying type for an enumeration except that the underlying type shall not be larger than int unless the value of an enumerator cannot fit in an int or unsigned int. If the enumerator-list is empty, the underlying type is as if the enumeration had a single enumerator with value 0. The value of sizeof() applied to an enumeration type, an object of enumeration type, or an enumerator, is the value of sizeof() applied to the underlying type.

In C++0x you can define the underlying type of an enum like follows:

enum foo : unsigned int { bar, baz };

Also note that the new strongly typed enums ("enum class") have a default underlying type of int.


In C and C++ they're ints. Type casting will not change them in the slightest, unless you change them to a narrower integer type (char, short).


This is different for the languages you tagged this question with.
In C and C++03, the underlying type of an enum is implementation defined. In C++0x, we can declare the underlying type ourselfs, called strongly typed enums (or enum classes):

// declares an enum with underlying type `unsigned char`
enum class MyEnum : unsigned char {/*...*/};


In C# you can specify the underlying type, and if you don't specify then the default is Int32.

public enum ThirtyTwoBitsWide
{
    This, Is, The, Default, Size
}

public enum EightBitsWide : byte
{
    Explicitly, Specify, The, Underlying, Size
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜