Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying size of enum type in C

Already read through this related question, but was looking for something a little more specific.

  • Is there a way to tell your compiler specifically how wide you want your enum to be?
  • If so, how do you do it? I know how to specify it in C#; is it similarly done in C?
  • Would it even be worth doing? When the enum value is passed to a function, will it be passed as an int-sized value regardless?
like image 752
Will Avatar asked Feb 02 '11 20:02

Will


People also ask

How do you specify the size of an enum?

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.

What size is enum in C?

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.

Why is sizeof enum 4?

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.


2 Answers

I believe there is a flag if you are using GCC.

-fshort-enums

like image 194
Nyx0uf Avatar answered Oct 08 '22 10:10

Nyx0uf


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.

like image 24
AnT Avatar answered Oct 08 '22 09:10

AnT