Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof enum in C language

Tags:

c

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 ?

like image 738
abhi Avatar asked Apr 02 '12 07:04

abhi


2 Answers

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.

like image 197
Some programmer dude Avatar answered Sep 29 '22 22:09

Some programmer dude


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.

like image 38
Alok Save Avatar answered Sep 29 '22 22:09

Alok Save