abhi
abhi

Reputation: 347

sizeof enum in C language

How can i know the size of the enum Days? Will it be equal to 7*4(sizeof(int)) = 28 ??
The printf() here is giving me value 4, How can it be explained?

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

Also we can use this as (enum Days)(0), which is similar to the integer array.If size is equal to 4 then how this array kind of behavior can be explained ?

Upvotes: 8

Views: 26409

Answers (5)

Jonathan
Jonathan

Reputation: 11

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

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409196

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

To know how many values are in an 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 enumerations in Days.

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

enum Foo
{
    bar = 5,
    NUM_FOO
};

In the above enum, NUM_FOO will be 6.

Upvotes: 19

littleadv
littleadv

Reputation: 20272

enum is usually sized as int. Its a type, not an array or struct, so I don't understand why you expect it to be 28.

Upvotes: 3

ouah
ouah

Reputation: 145839

In C, an enum type is an implementation defined integer type that can represent all the enum constants in the enum.

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

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

An enum type should not be confused with the enum constants. Enum constants are of type int.

Upvotes: 4

Alok Save
Alok Save

Reputation: 206546

It is implementation dependent. An enum is only guaranteed to be large enough to hold integer values.

Reference:
C99 Standard 6.7.2.2 Enumeration specifiers

Constraints
2 The expression that defines the value of an enumeration constant shall be an integer constant expression that has a value representable as an int.
...
4 Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined,128) but shall be capable of representing the values of all the members of the enumeration. The enumerated type is incomplete until immediately after the } that terminates the list of enumerator declarations, and complete thereafter.

Upvotes: 5

Related Questions