Enumeration
Enumeration gives us power to create our own data type in C. Also define what values the variable of this data type can take. By using enumeration we can simplify our programming code which helps us in maintaining code and reduce programming error.
In term of technical words, we can say enumeration as a user defined data type.
Enumeration is one kind on constant which takes values as integer.
Example:-
enum result
{
pass,fail
};
enum result Ram,Rohan;
where value can be assign to Ram and Rohan as below:-
Ram=pass;
Rohan=fail;
Internally, compiler treats the enumeration as integers. So a list of integer can be assigned to our own defined enumeration. It automatically assign value starting with 0. We can also provide our own desire value explicitly as below:-
enum result
{
pass=100,fail=30
};
enum result Ram,Rohan;
Different ways of working with enumeration:-
We can separately keep enumeration definition with variable declaration as below:-
In general term, an enumeration may be defined as:-
enum <name identifier> { member 1, member 2,…………, member n};
where enum is required keyword.
name identifier is the name that defines your enumeration.
member represent the individual identifier which can be assigned to variable of this type. The member name must be differ from one another. We can also specify its possible value.
Once the enumeration has been defined, corresponding enumeration variables can be declared as:-
storage-class enum <name identifier> variable 1, variable 2, ………….., variable n;
storage-class is optional storage class specifier.
enum is a required keyword.
name identifier is the name that defines your enumeration.
variable are enumeration variable of type specific.
Example:-
enum result
{
pass,fail
};
enum result Ram,Rohan;
We can combine enumeration definition with variable declaration as below:-
storage-class enum <name identifier> { member 1, member 2,…………, member n} variable 1, variable 2, ………….., variable n;
name identifier is optional in this case.
Example:-
enum result
{
pass,fail
}Ram,Rohan;
Please have a look to below example to calculate exponent of integer and floating point number
#include<stdio.h>
void main()
{
int i
enum week{sun,mon,tue,wed,thu,fri,sat};
for(i=sun;i<=sat;i++)
printf(“\n%d”,i);
}
OUTPUT:
0
1
2
3
4
5
6
Uses of enumeration data type
- Provide convenient way to associate constant values with names.
- Its an alternative to #define with an advantage of value generation for
- Although we declare the values for the enum type but compiler does not check weather the value assign to these variable is valid or not.
- Debugger is able to print the value of enumeration in symbolic form.
- The values in enumeration needs not to be distinct.
- Enumeration usually used to clarify the operation of a program.
- We can use enumeration variable as particularly useful as flags to carry out calculation.
- To make program more readable