Enumerated Data Type in C++
The enumerated data type gives you an oppurtunity to invent your own data type and
define what values the variable of this data type can take.
This can help in making programs more readable, which can be an advantage when a
program gets complicated or when more than one programmer working on this.
Using enumerated datatype can help you to reduce the errors.
Syntax :
enum identifier{v1,v2,v3,.......vn};
or
enum identifier{v1,v2,v3,.......vn}variable;
As an example one could invent a data type called company_size which can have three
possible values-small,medium,large.
The format of enum definition is similar to that of structure.
Here's how the example stated above can be implemented :
enum company_size
{
small,medium,large
};
enum company_size company1,company2;
or we can also write it as :
enum company_size
{
small,medium,large
}
company1,company2;
Like structures this declaration has two parts :
(a) The first part daeclares the data type and specifies its possible values.
These values are called enumerators.
(b) The second part declares variables of this data type.
Now we can give values to these variables :
company1=small;
company2=medium;
One thing should be remember that we can't use values that aren't in the original
declaration.
Thus, the following expression would cause an error :
company1=very small; //error
Internally, the compiler treats the enumerators as integers. Each values of the enum
constants corresponds to an integer starting with 0.
Thus,in above example values are:
small =0;
medium=1;
large=2;
We can give explicit values like :
enum company_size
{
small=500,medium=1000,large=1500
};
enum company_size company1,company2;
Complete example :
#include <iostream.h>
#include <conio.h>
enum company_size
{
small=500,medium=1000,large=1500
};
enum company_size company1,company2;
void main()
{
company1=small;
cout << company1;
getch();
}
Output :
500
Use :
Enumerated variables are usually used to clarify the operation of a program.
For example if we need to use comapny area/size in a program then we use enum
variables rather than declaring variables in main and assigning values them individually.
This will reduce the complexity of program and increase readibility.
Prev NEXT
2 comments:
great blog......simple n easy to understand!!!!!
thanks......
Casino & Sportsbook | Arizona | Mapyro
Casino & Sportsbook. 280 East Main St, Phoenix, AZ 85339. 경기도 출장샵 (480) 동해 출장안마 703-7788. Call 안양 출장안마 Now 양주 출장안마 · Full-Service. Open 24/7. Casino 김제 출장안마 Promotions. More Info. Menu, Photos, Phone
Post a Comment