![]() |
VOOZH | about |
In C, an enumeration (or enum) is a user-defined data type that contains a set of named integer constants. It is used to assign meaningful names to integer values, which makes a program easy to read and maintain.
Syntax:
enum enum_name {
n1, n2, n3, ...
};
where, n1, n2, n3, ... are identifiers mapped to integer values. By default, n1 is assigned 0, n2 is assigned 1, and each subsequent name is assigned a value incremented by 1.
Example: Declaring an enum "calculate"
Here, the name SUM is automatically assigned 0, DIFFERENCE is assigned 1 and so on. Enum names should follow the standard C variable naming rules. Uppercase is preferred for easy identification.
Enum constants must also be unique within the same scope. For example, the following code results in an error because both enums define the same constant PRODUCT in the global scope:
Output:
error: redeclaration of enumerator 'PRODUCT'
After enum is defined, we can create variables of that enum by using its specified name.
An enum variable can be initialized either with a name defined in the enum definition or directly with its integer value.
1 3
Though it is recommended to avoid using integers as enums loses their purpose when integer values are preferred in the use.
We can also manually assign desired values to the enum names as shown:
It is not mandatory to assign all constants. The next name will be automatically assigned a value by incrementing the previous name's value by 1. For example, n3 here will be (val2 + 1). Also, we can assign values in any order, but they must be integer only. Example:
3 2 3
In the above program, a is assigned the value 3, b is assigned 2, and c will automatically be assigned the value 3, as the enum values increment from the last assigned value. We can also confirm here that two enum names can have same value.
Enum definition is not allocated any memory, it is only allocated for enum variables. Usually, enums are implemented as integers, so their size is same as that of int. But some compilers may use short int (or even smaller type) to represent enums. We can use the sizeof operator to check the size of enum variable. Example:
4 bytes
The typedef keyword can be used to define an alias for an enum so that we can avoid using the keyword enum again and again. Example:
1
In the above program, we have used typedef to create a nickname Dirctn for the direction enum so that we can directly refer to it by using the nickname. It enhances the code readability.
Enums are extensively used in various real-world applications in programming, such as: