What are the enums in C++? How to use enums?

Introduction

What are the enums in C++? Enumeration is another way of defining user defined data types in C++. Though it has not much significance in programming but its a good way of understanding the basics of user defined data types. The syntax for enumeration is :

enum colorsnames { black, brown, red, orange, yellow, green, blue};

enum direction{left,right,front,back};

enum pets{dogs, cats, parrot, hen};

Here enum is the reserve keyword, colornames is actually the type_name and within bracket we have mentioned the values that this data type can take which is called enumerators and this process is called enumeration.

Another example is enum weekdays { sun,mon,tue,wed,thur,fri,sat};

It is important to note that by default the list within bracket has hidden values of integer. So, here black is assigned the value 0 and blue is assigned the value 6. Same is the case for weekdays: sun=0 and sat =6. Because of this hidden integer values we can perform some types of mathematical and comparison operations on enum data type.

Lets do an example for understanding this concept.

Example

enum weekdays { sun,mon,tue,wed,thur,fri,sat};

void main()

{

clrscr();

weekdays d1,d2; (here d1 and d2 are variable names of weekdays type and they can only have values from the list above)

d1=sun;

d2=fri;

int difference=d2-d1;

cout<<“days between” << d1<<” “<< d2<<” “<<diff<<endl;

if(d1>d2)

cout<<d1 <<“comes before<< ” “<< d2<<endl;

}

So this example explains how we can perform arithmetic and logical operations on enum data types. But this is not possible for all enum data types. Just like the case of colortypes. It does not convey any meaning if we add red into yellow or red is greater or less than black.

Assigning different values to enumerators

As we have seen by default the enumerators start at 0 and then each value is incremented by 1. We can also assign random values to enumerators. The following example illustrates this concept.

enum currency {pkr=1, dollar=155, pound=150, euro=100};

currency d1;

d1=dollar;

cout<<d1;

output= 155.

Example

enum itsaword { no,yes};

int main()

{
itsaword isword=no;

char ch=’a’;

int wordcount=0;

cout<<“enter a phrase”<<endl;

do

{

ch=getche();

if(ch==”||ch==’\r’)

{
if(isword==yes)

{

wordcount++;

isword=no;

}

else

if(isword==no)

isword=yes;

}

while(ch!=’\r’);

cout<<“word count is”<<wordcount<<endl;

return 0 }

Object Oriented Programming in C 4th Edition

lecture 2 Programming Fundamentals

Also read hereĀ 

Leave a Reply

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