A Quick Guide to Enums in C++

Ryan Flynn
3 min readFeb 14, 2021

Introduction

If you are completely new to C++ you may have run into the seemingly odd data type called an enum or an enumeration. Most tutorials I have seen tend to gloss over enums as just a collection of constants, but they never really talk about their use cases. In this blog I want to give a quick overview of what enums are and how you could use them in your C++ programs.

What is an Enum?

An enum or enumerated type is a user defined data type that holds a set of constant values. We usually use the keyword enum when we want a set of basic integers that will hold some sort of state in our program. Let’s say we are making a program and we want to know if someone has clicked the submit button or not. Well we can make an enum that helps us keep track of that like this:

So what am I doing here? Well the first thing we do when we declare an enum is to give it a descriptive name that details what state we are keeping track of. In this case we are looking at whether or not the submit button in our program was clicked or not. Then we are defining two possible values that the enum can have which are SB_Not_Clicked and SB_Clicked. Both of these values default to integers that hold 0 and 1 respectively. By default an enum will assign its values 0,1,2,3 etc. But you can always assign whatever integer value you want to those values. Now instead of referencing whether or not our button’s status is a 0 or a 1, we can reference these more descriptive values instead like so:

What I am doing here is I am creating a new variable called button_status that is of the type SubmitButtonStatus. Then I want it to say that it was clicked so now I give it the value of SB_Clicked. So now whenever I reference my button status instead of asking if it is 1 or 0, I can instead ask it whether or not it has been clicked. This is a much easier way to keep track of the state in your program. Instead of referencing obscure integers we can ask it whether or not it has the value that we have defined for it.

Conclusion

And that’s it! I hope that by explaining the use case of an enum you now have a better understanding of what it is and why we use it. Thanks for reading!

--

--