Enum Datatype in C++
How are Enum / Enumerated Datatype used in C++?
Explanation
Enum Datatype consist of a set of named values. These values can be used in indexing expressions.
The idea behind enumerated datatype is to create new data types that can take on only a restricted range of values.
Syntax:
enum enum-type-name { enumeration list } variable-list
Example :
#include <iostream.h> int main() { enum Fruits{orange, guava, apple}; Fruits myFruit; int i; cout << "Please enter the fruit of your choice(0 to 2)::"; cin >> i; switch(i) { case orange: cout << "Your fruit is orange"; break; case guava: cout << "Your fruit is guava"; break; case apple: cout << "Your fruit is apple"; break; } return 0; } |
Result :
Please enter the fruit of your choice(0 to 2)::2
Your fruit is apple
In the above example only the variable "i" is an integer. But using the enumeration the named values are used in a "switch case" statement with integer value "i".
This is how enum or enumerated datatype used in C++.