The Wayback Machine - https://web.archive.org/web/20240822170856/https://www.geeksforgeeks.org/enumeration-in-cpp/
Open In App

Enumeration in C++

Last Updated : 05 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Enumeration (Enumerated type) is a user-defined data type that can be assigned some limited values. These values are defined by the programmer at the time of declaring the enumerated type.

If we assign a float value to a character value, then the compiler generates an error. In the same way, if we try to assign any other value to the enumerated data types, the compiler generates an error. Enumerator types of values are also known as enumerators. It is also assigned by zero the same as the array. It can also be used with switch statements.

Syntax:

enum enumerated-type-name
{
    value1, value2, value3â€Ķ..valueN
};

For Example: If a gender variable is created with the value male or female. If any other value is assigned other than male or female then it is not appropriate. In this situation, one can declare the enumerated type in which only male and female values are assigned.

Enum in C++

The enum keyword is used to declare enumerated types after that enumerated type name was written then under curly brackets possible values are defined. After defining Enumerated type variables are created. 
Enumerators can be created in two types:-

  1. It can be declared during declaring enumerated types, just add the name of the variable before the semicolon. or,
  2. Besides this, we can create enumerated type variables as the same as the normal variables.
enumerated-type-name variable-name = value;

By default, the starting code value of the first element of the enum is 0 (as in the case of the array). But it can be changed explicitly.

Example:

enum enumerated-type-name{value1=1, value2, value3};

Also, The consecutive values of the enum will have the next set of code value(s).

Example:

//first_enum is the enumerated-type-name
enum first_enum{value1=1, value2=10, value3};

In this case, 
first_enum e;
e=value3;
cout<<e;

Output:
11

Example:

C++




// C++ Program to Demonstrate the Functioning of Enumerators
// with an example of Gender
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    // Defining enum Gender
    enum Gender { Male, Female };
  
    // Creating Gender type variable
    Gender gender = Male;
  
    switch (gender) {
    case Male:
        cout << "Gender is Male";
        break;
    case Female:
        cout << "Gender is Female";
        break;
    default:
        cout << "Value can be Male or Female";
    }
    return 0;
}


Output: 

Gender is Male

 

Example:

C++




// C++ Program to Demonstrate the Functioning of Enumerators
// with an Example of Year
#include <bits/stdc++.h>
using namespace std;
  
// Defining enum Year
enum year {
    Jan,
    Feb,
    Mar,
    Apr,
    May,
    Jun,
    Jul,
    Aug,
    Sep,
    Oct,
    Nov,
    Dec
};
  
// Driver Code
int main()
{
    int i;
  
    // Traversing the year enum
    for (i = Jan; i <= Dec; i++)
        cout << i << " ";
  
    return 0;
}


Output: 

0 1 2 3 4 5 6 7 8 9 10 11

 



Previous Article
Next Article

Similar Reads

How to Use HashMap in C++?
A HashMap is a data structure in which the elements are stored in key-value pairs such that every key is mapped to a value using a hash function. In C++, hash maps are implemented using the unordered_map container class. In this article, we will learn how to use HashMap in C++. Example: Input:Key="Apple"; Value=10Key="Mango"; Value=20Key="Cherry";
2 min read
How to Read From a File in C++?
In C++, file handling allows the users to read, write and update data into an external file. In this article, we will learn how to read some data from a file in C++. Read From a File in C++To read the content of a file in C++, we can use the std::ifstream (input file stream) to create the input stream to the file. We can then use the std::getline()
2 min read
How to Remove an Element from Vector in C++?
In C++, vectors are the same as arrays but they can resize themselves automatically when required as their storage is handled automatically by the container. In this article, we will learn how to remove a specific element from a vector in C++ Example: Input:myVector = {1, 2, 3, 4, 5, 6, 7, 8}Output:// removed element 5 from the vectormyVector = {1,
2 min read
C++ Exercises - C++ Practice Set with Solutions
Do you want to improve your command on C++ language? Explore our vast library of C++ exercise questions, which are specifically designed for beginners as well as for advanced programmers. We provide a large selection of coding exercises that cover every important topic, including classes, objects, arrays, matrices, and pointers. Master C++ with our
15+ min read
Top 100 C++ Coding Interview Questions and Answers (2024)
C++ is one of the most popular languages in the software industry for developing software ranging from operating systems, and DBMS to games. That is why it is also popular to be asked to write C++ Programs in live coding sessions in job placement interviews. This article provides a list of C++ coding interview questions for beginners as well as exp
15+ min read
C++ Program For Fibonacci Numbers
The Fibonacci numbers are the numbers in the following integer sequence.0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ........ In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation Fn = Fn-1 + Fn-2 with seed values  F0 = 0 and F1 = 1. Given a number n, print n-th Fibonacci Number.  Examples:  Input : n =
9 min read
GCD of Two Numbers in C++
GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest number that exactly divides both numbers. In this article, we will learn to write a C++ program to find the GCD of two numbers. Recommended PracticeLCM And GCDTry It!1. GCD Using Simple MethodThe idea is to find the minimum of the two numbers and then find th
4 min read
C++ Program For Merge Sort
Like QuickSort, Merge Sort is a Divide and Conquer algorithm. It divides the input array into two halves, calls itself for the two halves, and then it merges the two sorted halves. The merge() function is used for merging two halves. The merge(arr, l, m, r) is a key process that assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two s
7 min read
C++ Program For char to int Conversion
Here we will see how to convert char to int using a C++ program. There are 6 ways to convert char to int in C++: Using Typecasting.Using static_cast.Using sscanf().Using stoi().Using atoi().Using string stream. Let's discuss each of these methods in detail. 1. Using Typecasting Method 1: Declare and initialize our character to be converted.Typecast
5 min read
C++ Program For int to char Conversion
In this article, we will learn how to convert int to char in C++. For this conversion, there are 5 ways as follows: Using typecasting.Using static_cast.Using sprintf().Using to_string() and c_str().Using stringstream. Let's start by discussing each of these methods in detail. Examples: Input: N = 65 Output: A Input: N = 97 Output: a 1. Using Typeca
6 min read
Program to implement Singly Linked List in C++ using class
The linked list stores data in sequential storage, like arrays. Though the data are stored sequentially, the memory locations are not contiguous.Unlike an array, the linked list can store data of different data types.The below diagram represents the linked-list structure. In C++ the linked list can be represented with a class and a Node class separ
4 min read
C++ Program to check if a given String is Palindrome or not
Given a string S consisting of N characters of the English alphabet, the task is to check if the given string is a palindrome. If the given string is a palindrome, then print "Yes". Otherwise, print "No". Note: A string is said to be palindrome if the reverse of the string is the same as the string. For example, The string "racecar" is a palindrome
3 min read
C++ Keywords
C++ is a powerful language. In C++, we can write structured programs and object-oriented programs also. C++ is a superset of C and therefore most constructs of C are legal in C++ with their meaning unchanged. However, there are some exceptions and additions. TokenWhen the compiler is processing the source code of a C++ program, each group of charac
6 min read
Snake Game in C
In this article, the task is to implement a basic Snake Game. Below given some functionalities of this game: The snake is represented with a 0(zero) symbol.The fruit is represented with an *(asterisk) symbol.The snake can move in any direction according to the user with the help of the keyboard (W, A, S, D keys).When the snake eats a fruit the scor
6 min read
Const keyword in C++
In this article, the various functions of the const keyword which is found in C++ are discussed. Whenever const keyword is attached with any method(), variable, pointer variable, and with the object of a class it prevents that specific object/method()/variable to modify its data items value. Constant Variables:There are certain set of rules for the
10 min read
cout in C++
The cout object in C++ is an object of class iostream. It is defined in iostream header file. It is used to display the output to the standard output device i.e. monitor. It is associated with the standard C output stream stdout. The data needed to be displayed on the screen is inserted in the standard output stream (cout) using the insertion opera
3 min read
cin in C++
The cin object in C++ is an object of class iostream. It is used to accept the input from the standard input device i.e. keyboard. It is associated with the standard C input stream stdin. The extraction operator(&gt;&gt;) is used along with the object cin for reading inputs. The extraction operator extracts the data from the object cin which is ent
4 min read
Sorting a Map by value in C++ STL
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have equal key values. By default, a Map in C++ is sorted in increasing order based on its key. Below is the various method to achieve this: Method 1 - using the vector of pairs The idea is to copy all c
4 min read
First Come First Serve – CPU Scheduling (Non-Preemptive)
Simplest CPU scheduling algorithm that schedules according to arrival times of processes. The first come first serve scheduling algorithm states that the process that requests the CPU first is allocated the CPU first. It is implemented by using the FIFO queue. When a process enters the ready queue, its PCB is linked to the tail of the queue. When t
11 min read
Manipulators in C++ with Examples
Manipulators are helping functions that can modify the input/output stream. It does not mean that we change the value of a variable, it only modifies the I/O stream using insertion (&lt;&lt;) and extraction (&gt;&gt;) operators. Manipulators are special functions that can be included in the I/O statement to alter the format parameters of a stream.
6 min read
Conditional or Ternary Operator (?:) in C
The conditional operator in C is kind of similar to the if-else statement as it follows the same algorithm as of if-else statement but the conditional operator takes less space and helps to write the if-else statements in the shortest way possible. It is also known as the ternary operator in C as it operates on three operands. Syntax of Conditional
3 min read
Enum Classes in C++ and Their Advantage over Enum DataType
Enums or Enumerated type (enumeration) is a user-defined data type that can be assigned some limited values. These values are defined by the programmer at the time of declaring the enumerated type. Need for Enum Class over Enum Type: Below are some of the reasons as to what are the limitations of Enum Type and why we need Enum Class to cover them.
5 min read
Enumeration in C++
Enumeration (Enumerated type) is a user-defined data type that can be assigned some limited values. These values are defined by the programmer at the time of declaring the enumerated type. If we assign a float value to a character value, then the compiler generates an error. In the same way, if we try to assign any other value to the enumerated dat
3 min read
String Concatenation in C++
The string is a type of data structure used for storing characters. Concatenating strings in C++ is one of the most discussed topics related to strings. There are multiple methods to concat strings using user-defined methods, and a couple of methods for the concatenation of strings using pre-defined methods. Let's check on all of these methods. Met
5 min read
C++ Program to Make a Simple Calculator
A simple calculator is a device used to perform basic arithmetic operations such as addition, subtraction, multiplication, and division. It makes arithmetic calculations easier and faster. In this article, we will learn how to code a simple calculator using C++. Algorithm to Make a Simple CalculatorInitialize two float variables num1 and num2 to ta
2 min read
Check if given number is perfect square
Given a number n, check if it is a perfect square or not. Examples : Input : n = 36Output : Yes Input : n = 2500Output : YesExplanation: 2500 is a perfect square of 50 Input : n = 8Output : No Table of Content Using sqrt()Using ceil, floor and sqrt() functionsUsing Binary search:Using Mathematical Properties:Using sqrt()Take the floor()ed square ro
12 min read
Convert String to Char Array in C++
Here, we will build a C++ program to convert strings to char arrays. Many of us have encountered the error 'cannot convert std::string to char[] or char* data type' so let's solve this using 5 different methods: Using c_str() with strcpy()Using c_str() without strcpy()Using for loopUsing the address assignment of each other methodUsing data() (C++1
4 min read
C++ Program to check Prime Number
Write a C++ program to check whether the given number 'n' is a Prime number or not. A Prime Number is a natural number greater than 1 that has no positive divisors other than 1 and itself. For example: 5 is prime but 10 is not prime. Examples Input: N = 29Output: YesExplanation: 29 has no divisors other than 1 and 29 itself. Hence, it is a prime nu
6 min read
Bubble Sort in C++
Bubble Sort Algorithm is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity is quite high. Bubble Sort Example Consider an array to be mentioned below: arr[] = {5, 1, 4, 2, 8}First Trav
6 min read
C++ Program for QuickSort
Similar to the Merge Sort algorithm, the Quick Sort algorithm is a divide-and-conquer algorithm. It initially selects an element as a pivot element and partitions the given array around the picked pivot. Many different versions of quickSort pick pivot in different ways. Always pick the first element as a pivot (implemented below).Always pick the la
7 min read
Article Tags :
three90RightbarBannerImg