What is Enum?
The enumeration in C, helps the programmer to create user-defined data types, to make the code more easy and readable. Enum is almost similar to structure, as it can hold any data type, that the programmer may want, this is advantageous when the program gets complicated or when more than one programmer would be working on it, for the sake of better understanding. Enum saves time. Make the program more readable To define enums, the enum keyword is used enum variables can also take their corresponding integral value, starting from zero.
How to declare
an enum?
Declaring
an enum is almost similar to declaring a structure. We can declare an enum using
the keyword “enum”
followed by the enum name, and then stating its elements with the curly braces
“{}”, separated by commas.
enum color {
red,
green,
blue
};
- The first part of the above declaration declares the
data type and specifies its possible values. These values are called
“enumerators”.
- The second part declares the variables of these data-types
How does enum
works?
The variables
declared within the enum, are treated as integers, i.e.; each variable of the
enumerator can take its corresponding integral value, starting from zero(0).
That means in our above-discussed example,
- res
= 0
- green
= 1
- blue
= 2
The main
purpose of using enumerated variables is to ease the understanding of the
program. For example, if we need to employ departments in a payroll program,
it’ll make the listing easier to read if we use values like Assembly,
Production, Accounts, etc, rather than using 1,2, and 3. Let's take one more
example for understanding this
#include<stdio.h>
#include<string.h>
void main()
{
enum emp_dept //declaring enum emp_dept and its variables
{
assembly,
manufacturing,
accounts,
stores
};
struct employee //declaring srtucture
{
char name[30];
int age;
float bs;
enum emp_dept department;
};
struct employee e;
strcpy(e.name, "Coding Turtle"); //intializing employee details
e.age=21;
e.bs=125000;
e.department=stores;
printf("\n Name=%s",e.name);
printf("\n Age=%d",e.age);
printf("\n Basic Salary=%f",e.bs);
printf("\n Department=%d",e.department);
if(e.department==accounts)
printf("\n %s is an accountant",e.name);
else
printf("\n %s is not an accountant",e.name);
}
Output
Name=Coding Turtle
Age=21
Basic Salary=125000.000000
Department=3
Coding Turtle is not an accountant
Name=Vibush UpadhyayAge=22
Basic Salary=12500.000000
Department=3
Vibush Upadhyay is not an accountant
Comments
Post a Comment