Enumerations
An Enumeration allows you to create a type where the value in these variables is restricted to a list of available options. When you declare an enumeration, you are listing the values that are available to this type. The example in Figure x.y declares a type that can have the value ADD_COINS
or REMOVE_COINS
.
Enumerations - Why, When, and How
Use enumerations to capture places in your code where the value you want needs to be from a list of available options. A good example of this is the key codes in SplashKit. These are coded as an enumeration, listing the different keys that can be held down. Similarly, the mouse buttons are also an enumeration in SplashKit. These enumerations help you know what value to provide to achieve the result you want. For example, you can use KEY_RIGHT
for the right arrow key, or LEFT_BUTTON
for the left mouse button.
Internally, the compiler maps your enumeration options to numeric values. The first option is represented by the value 0
, the second is by the value 1
, and so on. You can specify the values for each option in the enumeration if you want. This can be useful if you have certain values you need each option to be for some reason.
The size of an enumeration is based on the size of the integer type used to represent its values.
In C/C++
Example
Underlying Representation and Casting
While we give names to the different options within our enums, we know that these are actually just integer values. This is why we need the default
branch in the example code - while it should be one of the valid options it may become any numeric value.
In general, you will work with enumerations through their named options, but sometimes you can take advantage of their underlying representation as a number. For example, you can take advantage of using the numeric values when you read a value from the user.
To do this, you need to tell the compiler to change the type from an integer to the enum type. This is called a type cast.
The following code demonstrates how to use this idea to read in a warning level value. Here we use the function call type cast syntax. When we do this, we need to make sure that the integer values align with the value in the enumeration.