Â
Enumeration in C++ :Â
Enumeration in another kind of user-defined datatype in C++. It is generally used to store constant values or set of constant values. It also makes a program easy to read and maintain. It is denoted with the keyword " enums ".
Syntax to define an enum :Â
enum enum_name{const1, const2, ....... };
If this data-type is used for any variable then that variable becomes enum type and will be storing the constants or set of constants.
Each enum constant has a default value starting from 0 to n but it can be changed manually too while writing programÂ
For Example :-Â
enum season_names{Winter, Summer, Monsoon, Spring};
In the above example the default value of Winter is 0 followed by Summer which is 1 and followed by other seasons. Now in order to change the default values we have to declare the values explicitly in the enum.Â
For Example :-Â
enum season_names{Winter = 2, Summer = 5, Monsoon = 3, Spring = 4};
Now we got to know how to define an enum, so now we will see how to get / use the values or elements of enums in any program.Â
Â
In order to use the values or elements of enums there are different ways to declare an enum variable the ways are given below : -Â
For Example :-Â
// enum defined
enum season_names{Winter, Summer, Monsoon, Spring};
// declaring enum variable
season_names s1 = Monsoon;
season_names s2(Spring);
season_names s3{Winter};
cout<<"season name is "<<s1;
cout<<"season name is "<<s2;
cout<<"season name is "<<s3;
This is how we use enums properly in any program.
Now let's have a look on a program based on enums definition , declaration and everything altogether.
For Example :-Â
#include<iostream>
using namespace std;
int main()
{
enum colour //defining an enum called colour
{
violet, //by default value o is assigned
indigo, //value is incremented by 1, hence value assigned is 1
blue, //value assigned is 2
green, // value assigned is 3
yellow, // value assigned is 4
orange, //value assigned is 5
red // value assigned is 5
}; // the defining of an enum must end with a semicolon
//different ways of defining variables of enumeration type colour
colour c1 = green;
colour c2(orange);
colour c3{blue};
cout << "The value of colour 1 is: " << c1 << endl;
cout << "The value of colour 2 is: " << c2 << endl;
cout << "The value of colour 3 is: " << c3 << endl;
return 0;
}
Post a Comment
FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP