
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Enumerate over an enum in C++
Enumeration is a user defined datatype in C/C++ language. It is used to assign names to the integral constants which makes a program easy to read and maintain. The keyword “enum” is used to declare an enumeration.
The following is the syntax of enums.
enum enum_name{const1, const2, ....... };
Here, enum_name − Any name given by user. const1, const2 − These are values of type flag.
The enum keyword is also used to define the variables of enum type. There are two ways to define the variables of enum type as follows −
enum colors{red, black}; enum suit{heart, diamond=8, spade=3, club};
Example
#include <iostream> using namespace std; enum colors{red=5, black}; enum suit{heart, diamond=8, spade=3, club}; int main() { cout <<"The value of enum color : "<<red<<","<<black; cout <<"\nThe default value of enum suit : "<< heart << "," << diamond << "," << spade << "," << club; return 0; }
Output
The value of enum color : 5,6 The default value of enum suit : 0,8,3,4
Enumerate over an Enum. This is easy process, we can create for loop and here we will start from the first type, and end with the end type. Let us see the code.
Example
#include <iostream> using namespace std; enum suit{heart, diamond, spade, club}; int main() { for(int i = heart; i<=club; i++) { cout << "Card Type : " << i << endl; } }
Output
Card Type : 0 Card Type : 1 Card Type : 2 Card Type : 3
- Related Articles
- How to enumerate an enum with String type?
- Iterating over Enum Values in Java
- Java Program to Iterate over enum
- Haskell Program to Iterate over enum
- Enumerate() in Python
- Enum in C
- Enum in C#
- How to define an enumerated type (enum) in C++?
- How to loop through all values of an enum in C#?
- Comparing enum members in C#
- How to convert an enum type variable to a string in C++?
- Can we extend an enum in Java?
- Enum with Customized Value in C#
- How to call another enum value in an enum's constructor using java?
- C# Enum IsDefined Method

Advertisements