C++Tutorials

enum in C++

Enum is also called as enumeration. An enumeration is a user-defined data type that consists of integral constants. To define an enumeration, the keyword enum is used.

It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc. The C++ enum constants are static and final implicitly.

Let’s understand it by looking below example.

enum week { sunday, monday, tuesday, wednesday };

Here, the name of the enumeration is weeek and sunday,monday,tuesday are the value type of week.

Example : 1 C++ Enumeration

#include <iostream>  
using namespace std;  
enum week { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };  
int main()  
{  
    week day;  
    day = Friday;  
    cout << "Day: " << day+1<<endl;  
    return 0;  
}     

Output:

Day: 5

Example: 2 Changing Default Value of Enums

#include <iostream>
using namespace std;

enum seasons { spring = 34, summer = 4, autumn = 9, winter = 32};

int main() {

    seasons s;

    s = summer;
    cout << "Summer = " << s << endl;

    return 0;
}

Output

Day 4

Advantages of enum

  • enum improves type safety
  • enum can be easily used in switch
  • enum can be traversed
  • enum can have fields, constructors and methods
  • enum may implement many interfaces but cannot extend any class because it internally extends Enum class

Disadvantages of enum

  • The enumerators have no scope
  • The enumerators implicitly convert to implicitly to int
  • The enumerators pollute the global namespace
  • The type of the enumerator is not defined. It just has to be big enough to hold the enumerator.

Shaiv Roy

Hy Myself shaiv roy, I am a passionate blogger and love to share ideas among people, I am having good experience with laravel, vue js, react, flutter and doing website and app development work from last 7 years.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button