Enumeration is a data type, which is coded as enum, may be used to define user's own data type and define values that the variable can take. The enumeration type is an integral data type. This can help in making program more readable. enum definition is similar to that of a structure. Its syntax is as follows:
enum typename { enumerator_list_of_objects};
Declaration of enum has two parts:
a) First part declares the data type and specifies the possible values, called 'enumerators'.
b) Second part declares the variables of this data type.
The syntax is illustrated below with enumeration of working days of a week.
enum Workingdays {Monday, Tuesday, Wednesday, Thursday, Friday};
In this case, Monday, Tuesday, etc., are of type 'Workingdays'. Also, in the given declaration, Monday would have a numerical value 0; Tuesday would have value 1, Wednesday 2, and so on. Now, if you put Monday= 1 as illustrated below, then Tuesday would have value 2, Wednesday 3, and so on.
enum Workingdays {Monday=l, Tuesday, Wednesday, Thursday, Friday};
The arithmetic operation may be carried out on the above enumerators, which will have integral constant values as explained. Thus, with this declaration the expression
Tuesday + Friday - Wednesday;
will evaluate to 2 + 5 - 3 = 4.
The enum may also be used to define a number of integral constants, as illustrated below.
enum Value {X = 100, Y = 100, z = 400};
enum Numbers {K = 11, R, S, X = 5, Y, Z};
For the last line, the values of R, S, Y, and z would be assigned as follows:
R = K+1 =12, S =K+2 =13, Y = x+1= 6, Z = X+2= 7.
The application of enum type is illustrated in Program
Illustrates enum type variables.
#include <stdio.h>
main()
{
enum Day{ Monday =1, Tuesday, Wednesday, Thursday};
enum { A= 3, B , C , Z = 400, X, Y };
printf("Wednesday = %d\n", Wednesday);
printf("B = %d \t C = %d\n", B,C);
printf("X = %d \t Y = %d\n", X,Y);
printf("Thursday/Tuesday = %d\n", Thursday/Tuesday);
}
The expected output is given below.
Dinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.
Related Articles
Basic Courses
Advance Courses