Why would I use enum as a type?
I saw a post on SO about using boolean types in C. One of the answers listed four ways to implement boolean types, the second and third way being:
typedef enum { false, true } bool;
and
typedef int bool;
enum { false, true };
The first one confused me at first because I had never seen an enum
being used as a type. Since enum
defines integer constants, I thought it was the same thing as the second one but slightly more confusing.
So, how does using enum
as a type work? Is there a difference between using enum
as a type and using an integer type, defining the enum
elsewhere? Most importantly, why would someone use enum
as a type?
Solution 1:
Generally in programming, enums
are used for creating lists of defined final values. And because booleans
can be either true
or false
, it is a good fit to implement it this way.
The first code bit you included is quite simple, it defines a type called bool
as an enum
that can be either true
or false
. Why it's defined here in the enum is because this way you won't get an error, when using true
/false
as values in your code. Also, there's a reason, why false
is listed first - on the index 0 and true
is on the index 1. Can you guess? ...You can convert enum
element to int
by its index (meaning: this way when you work with false
value, you are basically working with 0).
The second code is very similar, it defines type bool
, but as an integer
instead. That's because that's how you normally represent bools
in C = 1 (or any other int to get true
) or 0 (false
). The definition of enum
here is again just to prevent from getting an error, when using true
and false
as values. Again the values are positioned this way for a reason - thanks to which you can just do if (true)
or if (false)
and it will work as intended (the reason is described above).