Programming: Enums

Suppose you wanted to represent the current state of a traffic light. A simple traffic light can have one of three states: red, yellow, or green. What would be the best way to represent each of these states? You could represent each one as a string. However, strings use more memory than necessary for such a simple representation. What if each color was instead represented by an integer? For example, red is designated by 0, yellow by 1, and green by 2. This simplifies the representation while not consuming as much memory. However, we lose some clarity if we leave these states as just numbers. Luckily, we can use enums to get the best of both worlds.


An enum, short for enumeration, is a user-defined list of names that have associated numerical values with each name. Enums are useful for giving meaningful code names to numbers that are meant to represent something else other than a number. For instance, an enum containing the names RED, YELLOW, and GREEN will give each of those names a numerical value. By default, the first name, RED, will be equivalent to 0, YELLOW will be equivalent to 1, and GREEN will be equivalent to 2. Enums work similarly to macros in the sense that every instance of RED, YELLOW, or GREEN will be instead substituted in the code by its associated number. The biggest difference is that enums are limited by scope and are evaluated at runtime rather than being preprocessed.

Since enums are user-defined data types, you can define a variable as a type of that enum. For example, the following declaration creates an enum called traffic_light_color:

enum traffic_light_color { RED, YELLOW, GREEN };

If we created a new variable…

enum traffic_light_color myColor;

myColor can have a value of RED (0), YELLOW (1), or GREEN (2).

(Learn more: https://www.geeksforgeeks.org/enumeration-enum-c/

To learn more about macros, enum, and typedef import the following project into CCS:

https://github.com/VT-Introduction-to-Embedded-systems/macro_enum_typedef