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 ?
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With