Enum
Enums are a useful feature in C programming language that allows programmers to create custom data types. These data types are restricted to a list of values specified by the programmer. This means that only one value from the list can be stored in the enum data type at any given time. Enums treat the list of values as numbers and allow programmers to use them in their code to improve readability and maintainability.
To create an enum in C, the keyword "enum" is used followed by the name of the enum data type and a list of values enclosed in braces. Here's an example:
copy
enum boolean
{
false, true // it is actually 0 and 1
};
In this example, we are creating an enum data type called "boolean" with two values, "false" and "true". Note that "false" is assigned the value of 0 and "true" is assigned the value of 1. These values are treated as integers by the compiler.
Once the enum is defined, it can be used in the code just like any other data type. Here's an example:
copy
enum boolean a;
a = true;
printf("%d\n", a);
a = false;
printf("%d\n", a);
In this example, we declare a variable "a" of type "boolean" and assign it the value "true". We then print the value of "a" which is 1. Next, we assign the value "false" to "a" and print its value which is 0.
Enums can also be used to improve the readability of code. For example, if we wanted to create an enum for different currencies, we could do the following:
copy
enum currency
{
rupees = 1, dollor, pound, ruble // it is actually 1 2 3 and 4
};
enum currency
{
rupees = 1, dollor, pound, ruble // it is actually 1 2 3 and 4
};
In this example, we are creating an enum data type called "currency" with four values, "rupees", "dollor", "pound", and "ruble". Note that we are assigning the value "1" to "rupees" and the rest of the values are assigned consecutive integers. This is because enums treat the list of values as numbers.
We can then use this enum in our code like this:
copy
enum currency choice;
printf("Choose any one your currency\n 1. Rupees\n 2. Dollor\n 3. Pound\n 4. Ruble\n");
scanf("%d", &choice);
if (choice == rupees)
{
printf("I am Rupees\n");
}
else if (choice == dollor)
{
printf("I am Dollor\n");
}
else if (choice == pound)
{
printf("I am Pound\n");
}
else if (choice == ruble)
{
printf("I am Ruble\n");
}
else
{
printf("Wrong choice\n");
}
In this example, we declare a variable "choice" of type "currency" and prompt the user to choose a currency. We then use if-else statements to check the value of "choice" and print the corresponding currency.
In conclusion
enums are a powerful tool in C programming language that can help improve the readability and maintainability of code. They allow programmers to create custom data types with a restricted list of values and treat them as numbers. By using enums, programmers can make their code more intuitive and easier to understand.