Already read through this related question, but was looking for something a little more specific.
int
-sized value regardless?The C standard specifies that enums are integers, but it does not specify the size. Once again, that is up to the people who write the compiler. On an 8-bit processor, enums can be 16-bits wide. On a 32-bit processor they can be 32-bits wide or more or less.
In C language, an enum is guaranteed to be of size of an int . There is a compile time option ( -fshort-enums ) to make it as short (This is mainly useful in case the values are not more than 64K). There is no compile time option to increase its size to 64 bit.
C++ - Size of an enum Is size of an enum always 4? The standards doesn't specify the size of an enum. The size of an enum is the size of the underlying integral type that can hold the biggest enumerated value, usually starts from int(4bytes) , if int cannot hold the values the compiler choose a bigger type.
I believe there is a flag if you are using GCC.
-fshort-enums
Is there a way to tell your compiler specifically how wide you want your enum to be?
In general case no. Not in standard C.
Would it even be worth doing?
It depends on the context. If you are talking about passing parameters to functions, then no, it is not worth doing (see below). If it is about saving memory when building aggregates from enum types, then it might be worth doing. However, in C you can simply use a suitably-sized integer type instead of enum type in aggregates. In C (as opposed to C++) enum types and integer types are almost always interchangeable.
When the enum value is passed to a function, will it be passed as an int-sized value regardless?
Many (most) compilers these days pass all parameters as values of natural word size for the given hardware platform. For example, on a 64-bit platform many compilers will pass all parameters as 64-bit values, regardless of their actual size, even if type int
has 32 bits in it on that platform (so, it is not generally passed as "int-sized" value on such a platform). For this reason, it makes no sense to try to optimize enum sizes for parameter passing purposes.
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