Sizeof enum in C

How to find out the size of the Days listing? Will it be equal to 7*4(sizeof(int)) = 28 ?
printf() here gives me a value of 4 , how can this be explained?

 enum Days { saturday, sunday , monday , tuesday, wednesday, thursday, friday } TheDay; printf("%d", sizeof(enum Days)); 

We can also use this as (enum Days) (0), which looks like an integer array. If the size is 4, then how can this array type behavior be explained?

+8
c
source share
5 answers

In C, all enums are int integers of time, which explains why sizeof(Days) == 4 for you.

To find out how many values ​​are in enum , you can do something like this:

 enum Days { saturday, sunday, monday, tuesday, wednesday, thursday, friday, NUM_DAYS }; 

Then NUM_DAYS will be the number of transfers in Days .

Note that this will not work if you change the enumeration values, for example:

 enum Foo { bar = 5, NUM_FOO }; 

In the above listing, NUM_FOO will be 6 .

+17
source share

It depends on the implementation. Enumeration is guaranteed only to store integer values.

Reference:
C99 Standard 6.7.2.2 Listing Qualifiers

Limitations
2 An expression defining the value of an enumeration constant must be an integer constant expression that has a value represented as int.
...
4 Each enumerated type must be compatible with char, a signed integer, or unsigned integer. The choice of type is determined by the implementation, 128) but must be able to display the values ​​of all members of the enumeration . The enumerated type is incomplete until immediately after it the list of declarations of the enumerator is completed and is not completed after that.

+5
source share

In C, an enumeration type is an integer implementation type that can represent all enumeration constants in an enumeration.

With gcc , if there is no negative value in the enum constants, the specific implementation type is unsigned int otherwise - int .

http://gcc.gnu.org/onlinedocs/gcc/Structures-unions-enumerations-and-bit_002dfields-implementation.html

An enumerated type should not be confused with enumeration constants. Continuum constants are of type int .

+3
source share

enum usually has an int size. Its type, not an array or structure, so I don't understand why you expect this to be 28.

+2
source share

With the compiler I'm using right now, sizeof(enum) depends on the biggest value. If all values ​​are enum <= 0xFF , then the size is 1 byte, but if there is a value 0x100 , then the size will be 2 bytes ... Just adding values ​​to enum can change the result of sizeof(MyEnum)

0
source share

All Articles