Skip to main content
C++

Enumerated types (Enum) in C++

By January 10, 2020No Comments
Enum is a user defined data type in C++ whose value is equal to some user defined values. For example:
//use enum keyword
// name of enum variable is "week"
#include <iostream>
using namespace std;

enum week { Moonday, Tuesdayz, WednesOhday, ThursdayNow, Fridayay, Saturdayikes, Sundayeez }; 
int main(){
   week my_day;
   my_day = WednesOhday; 
   cout<<  my_day;   
   return 0;
}
Enum is useful for switch cases, when we expect a variable to have only one of the possible set of values. For example, we can change the code to:
#include <iostream>
using namespace std;

enum week { Moonday, Tuesdayz, WednesOhday, ThursdayNow, Fridayay, Saturdayikes, Sundayeez }; 
int main(){
   week my_day;
   my_day = week::WednesOhday; 
   if(my_day == week::WednesOhday){
   cout<<  "It's WednesOhday";  
   } else {
   cout << "Not WednesOhday!";
   } 
   return 0;
}

Leave a Reply