Ad Code

What is enum keyword in C++?

What is enum keyword in C++?  Kindly give small code snippet to understand it better?


abstract
enum(enumeration) is a user-defined type consisting of a set of enumerators( enumerator --- named integer constant)

compatible
Any modern C++ compiler
The enum is declared as:
enum enum-type-name { enum-list } enum-variable;
In this form, enum-type-name is optional. However, if you want to use enum type in several places, it is better to use another way of enum declaration:
enum enum-type-name { enum-list };

//... (and somewhere below)

enum enum-type-name enum-variable;
Of course, in the second case enum-type-name cannon be omitted.
Example: declaring enumeration type of automobile companies
source code: C++

enum e_acomany {
Audi,
BMW,
Cadillac,
Ford,
Jaguar,
Lexus
Maybach,
RollsRoyce,
Saab
};


After declaration, it is possible to use enum-type-name as user-defined type. Enumeration variable or constant may take on only values from enum-list.
Following example demonstrates basic enumeration usage:
source code: C++

e_acompany my_car_brand;
my_car_brand = RollsRoyce;
//...

if (my_car_brand == Ford)
cout << "Hello, Ford-car owner!" << endl;


Enumerators are stored by compiler as an integers: by default, first enumerator is 0, next enumerator value is previous enumerator value + 1. When defining enumeration it is possible to specify integer constant for every enumerator, see example:
source code: C++

enum e_acomany {
Audi=4,
BMW=5,
Cadillac=11,
Ford=44,
Jaguar=45,
Lexus,
Maybach=55,
RollsRoyce=65,
Saab=111
};

By the rule "next enumerator value is previous + 1", the value of "Lexus" enumerator is 46
Enumerations are sometimes used instead of integer constants, like in this program:
source code: C++

#include <iostream>
using namespace std;

enum e_usflcnst{
CATLIFE_FACTOR = 7
};

int main()
{
int age;
cout << "Enter your age: ";
cin >> age;
age /= CATLIFE_FACTOR;
cout << "If you were cat, you would be " << age << endl;
}
Reactions

Post a Comment

0 Comments