It gives an opportunity to invent our own data type and define what values the variable of this data type can take. This also helps in making the program more readable, which can be an advantage when a program gets complicated or when more than one programmer would be working on it. Using enumerated data type can also help in reducing programming errors.
One could invent a data type called mar_status which can have four possible values
single,married ,divorced or widowed.
e.g. Married for instance has the same relationship to the variable mar_status as the number 15 has with an integer variable.
Format of the enum defination is similar to that of a stucture. Example stated above can be implemented as shown below.
enum mar_status
{
single,married,divorced,widowed;
};
enum mar_status person1,person2
This decleration has two parts:
- First Part declares the data type and specifies its possible values.These values are called enumerators
- Second part declares the variable of this data tyoe.
A user-defined data type is enumeration these consists of integral constants and each integral constant is give a name. Enumerated data type is defined with the enum keyword.
enum type_name{ value1, value2,...,valueN };
The enumerated data type is type_name and values of type type_name are value1, value2,....,valueN
The default value of value1 will be equal to 0, value2 will be 1 and so on but, the programmer can change the default value according to their need.
// Changing the default value of enum elements
enum suit{
club=1;
diamonds=12;
hearts=14;
spades=5;
};
Declaration of enumerated variable
enum boolean{
false;
true;
};
enum boolean answer;
Variable answer is declared which is of type enum boolean.
Example of enumerated type
#include
enum month{ jan ,feb ,mar ,apr ,may ,jun, jul ,aug ,sep ,oct ,nov ,dec};
int main(){
enum month today;
today=apr;
printf("%d month",today+1);
return 0;
}
Output of above code is
4 month
0 Comment(s)