Several reasons:
Reason 1: Flexibility:
enum lickahoctor { yes = 0, no = 1, maybe = 2 };
declares an enumeration. You can use the values yes
, no
and maybe
anywhere and assign them to any integral type. You can also use this as a type, by writing
enum lickahoctor myVar = yes;
This makes it nice because if a function takes a parameter with the type enum lickahoctor you'll know that you can assign yes
, no
or maybe
to it. Also, the debugger will know, so it'll display the symbolic name instead of the numerical value. Trouble is, the compiler will only let you assign values you've defined in enum lickahoctor
to myVar
. If you for example want to define a few flags in the base class, then add a few more flags in the subclass, you can't do it this way.
If you use an int instead, you don't have that problem. So you want to use some sort of int, so you can assign arbitrary constants.
Reason 2: Binary compatibility:
The compiler chooses a nice size that fits all the constants you've defined in an enum. There's no guarantee what you will get. So if you write a struct containing such a variable directly to a file, there is no guarantee that it will still be the same size when you read it back in with the next version of your app (according to the C standard, at least -- it's not quite that bleak in practice).
If you use some kind of int instead, the platform usually guarantees a particular size for that number. Especially if you use one of the types guaranteed to be a particular size, like int32_t
/uint32_t
.
Reason 3: Readability and self-documentation
When you declare myVar above, it's immediately obvious what values you can put in it. If you just use an int, or an uint32_t
, it isn't. So what you do is you use
enum { yes, no, maybe };
typedef uint32_t lickahoctor;
to define a nice name for the integer somewhere near the constants that will remind people that a variable of this type can hold this value. But you still get the benefit of a predictable, fixed size and the ability to define additional values in subclasses, if needed.
Reason 4: Support for bitfields
enum-typed variables only support assigning exactly one value from their options. So if you're trying to implement a bit field, you can't type it as a bitfield. Furthermore, you need to use unsigned variables to avoid sign extension from screwing you over.