C Enum

Summary: in this tutorial, you will learn about C enum keyword, which defines enumeration types, to enhance your code readability.

Let’s take a look at a sample program.

C enumThe program is very simple. It asks you to choose a favorite color by entering 0, 1 or 2. If you look at the code, you will see that it is not perfect in term of readability. In the switch case statement, we used integer numbers to represent colors. It would be great if we can use symbolic names like red, green and blue to represent integer constants 0, 1 and 2. That is our wish, and C has the answer.

C provides developers with special types called enumerated types or enum to declare symbolic names that represent integer constants. Its main purpose is to enhance the readability of the code. An enumeration consists of a group of symbolic integers.

For example, we can declare an enumeration for colors as follows:

In the statement above:

  • enum is the keyword to declare a new enumeration type
  • color is the tag name that you can use later as a type name. The tag name must be unique within its scope. This tag name is also optional so you can omit it.
  • Inside the curly brackets {} is a set of named integers. This set is also known as enumeration constants, enumeration sets, enumerators or just members.

By default, the first enumeration member in the set has value 0. The next member has the value of the first one plus 1. So in this case red = 0, green = 1 and blue = 2. You can explicitly assign an enumeration member to another value using assignment operator ( =) when you define the enumeration type.

The enumeration members must follow the rules:

  • An enumeration set may have duplicate constant values. For instance, you can assign 0 with two enumeration members.
  • The name of enumeration member must be unique within its scope. It means its name should not be the same as other member or variable name.

How to use C enum type

If you declare a variable with enumeration type, the value of that value must be one of the values of the enumeration members. For example, you can declare a variable called favorite_color as a variable of the color type.

C enum example

You can rewrite our example above using enum types. Here is the rewritten code:

C enum size

There are many developers asking a question: What is the size of an enum? In fact, C enum types realize on the C compiler to choose actual type that stores the constants based on the enumeration types definition. However it is guaranteed that enum type is always large enough to hold integer (int) values.

Convert integer into enum

How do you convert an integer into an enum ? You need to explicitly use type cast. The following example illustrates how to convert an integer into an enum:

In this tutorial, you’ve learned how to use C enumeration types to make your code easier to read and maintain.

  • Was this tutorial helpful ?
  • YesNo