Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Definition and Declaration of Enum in C++
2.1.
Here's a basic example to illustrate:
3.
Why Do You Use Enums?
3.1.
Improved Readability
3.2.
Type Safety
3.3.
Maintainability
3.4.
Switch Statement Integration
3.5.
Scoped and Strongly-Typed Enums
4.
Enum with Flags
4.1.
Defining the Enum
4.2.
Using the Enum with Flags
4.3.
Checking Permissions
5.
Examples
5.1.
Example 1: Basic Enum Usage
5.2.
Example 2: Enum with Switch Case
5.3.
Example 3: Scoped Enum (Enum Class)
6.
Frequently Asked Questions
6.1.
Can Enumerations in C++ Contain Values Other Than Integers?
6.2.
How Do You Convert an Enum to a String in C++?
6.3.
What's the Difference Between Regular Enums and Enum Classes in C++?
7.
Conclusion
Last Updated: Jul 1, 2024
Easy

Enumeration in C++

Author Sinki Kumari
0 upvote

Introduction

C++ is a programming language that's as versatile as it is powerful, a go-to for many developers for its efficiency and control. Within its toolkit is a feature known as enumeration. This article aims to unpack the concept of enumeration in C++, shedding light on their definition, declaration, and practical applications.

C++ Enum

By the end of this discussion, you'll have a clear understanding of what enumeration are, why they're used, and how to implement them effectively in your code.

Definition and Declaration of Enum in C++

Declaring an enumeration in C++ is straightforward. It involves specifying a new enum type name and then listing the desired identifiers inside curly braces. These identifiers are the enumeration constants, and by default, they're assigned integer values starting from 0, incrementing by 1 for each subsequent value. However, you can also explicitly assign values to them.

Here's a basic example to illustrate:

enum Weekday { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
You can also try this code with Online C++ Compiler
Run Code


In this case, Monday will be 0, Tuesday 1, and so on. If you want to start the week from Sunday with a value of 1, it can be declared as:

enum Weekday { Sunday = 1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
You can also try this code with Online C++ Compiler
Run Code


Now, Sunday is 1, and Monday automatically becomes 2, continuing in sequence.

The power of enums is evident when you need to work with a set of related constants. By grouping these constants, your code becomes more organized and easier to understand. Moreover, enums can be used in switch statements, functions, and as return types, making them extremely versatile.

Why Do You Use Enums?


Enums are a significant part of C++ for several reasons, primarily revolving around code readability, safety, and maintainability. Let’s delve into these aspects:

Improved Readability

Enums replace numeric codes or statuses with meaningful names. Imagine a function that returns numbers for error codes. It's far easier to understand and remember ERROR_FILE_NOT_FOUND than to recall what 2 signifies.

Type Safety

Enums provide a way to define a variable that must be one of the enumerated values, reducing errors. For instance, if you have an enum for colors, the compiler will prevent assigning a non-color value to a variable of this enum type.

Maintainability

With enums, adding new values is simple and doesn't affect the existing code. This can be incredibly beneficial when working on large projects or with a team. If you need to add a new day of the week (like a fictional "Funday"), you just add it to the enum without disrupting the rest of your code.

Switch Statement Integration

Enums work seamlessly with switch statements in C++. This is particularly useful for branching logic based on enum values, making the code cleaner and more manageable.

Scoped and Strongly-Typed Enums

C++11 introduced scoped enums (enum class), providing better type safety and avoiding name clashes, as they don't implicitly convert to integers.

Enum with Flags

In C++, enums can also be used to represent a set of flags. This is particularly useful in scenarios where you need to represent a combination of options or states. Essentially, you can 'flag' multiple values within a single enum variable by using bitwise operators. This is achieved by assigning enum values that are powers of 2.

Here’s how you can define and use an enum with flags:

Defining the Enum

enum FilePermissions {
    Read = 1,    // 1 << 0
    Write = 2,   // 1 << 1
    Execute = 4  // 1 << 2
};
You can also try this code with Online C++ Compiler
Run Code


In this example, Read, Write, and Execute are file permissions, each represented by a single bit in a binary number.

Using the Enum with Flags

You can combine these flags using the bitwise OR operator (|) to represent multiple permissions.

int myPermissions = Read | Execute;
You can also try this code with Online C++ Compiler
Run Code


This sets myPermissions to a value that represents both reading and executing rights. To check if a specific permission is set, you can use the bitwise AND operator (&).

Checking Permissions


if (myPermissions & Read) {
    // The Read permission is set
}
You can also try this code with Online C++ Compiler
Run Code


This technique allows for efficient and readable representation of combinations of states or options.

Examples

Example 1: Basic Enum Usage

Let's start with a simple example where we define and use an enum for basic colors.

enum Color {
    Red, Green, Blue
};
Color favoriteColor = Blue;
if (favoriteColor == Blue) {
    std::cout << "The favorite color is blue!" << std::endl;
}
You can also try this code with Online C++ Compiler
Run Code


Here, we define an enum Color and set a variable favoriteColor to Blue. The if-statement checks if favoriteColor is blue, and if so, prints a message.

Example 2: Enum with Switch Case

Enums are commonly used with switch statements for clear, concise code.

enum Day {
    Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
};

Day today = Wednesday;

switch(today) {
    case Monday:
        std::cout << "Start of the work week." << std::endl;
        break;
    case Friday:
        std::cout << "Almost weekend!" << std::endl;
        break;
    case Sunday:
        std::cout << "Weekend!" << std::endl;
        break;
    default:
        std::cout << "Just another day." << std::endl;
        break;
}
You can also try this code with Online C++ Compiler
Run Code


In this example, we use an enum to represent days of the week and a switch statement to execute different blocks of code depending on the value of today.

Example 3: Scoped Enum (Enum Class)


C++11 introduced scoped enums for better type safety and scope control.

enum class TrafficLight {
    Red, Yellow, Green
};

TrafficLight light = TrafficLight::Red;

if (light == TrafficLight::Red) {
    std::cout << "Stop!" << std::endl;
}
You can also try this code with Online C++ Compiler
Run Code


Here, TrafficLight is a scoped enum, and its values are accessed with the scope resolution operator ::.

Frequently Asked Questions

Can Enumerations in C++ Contain Values Other Than Integers?

Enums primarily use integers, but you can explicitly cast them to other types, like char or string, for specific purposes.

How Do You Convert an Enum to a String in C++?

C++ doesn't directly support enum-to-string conversion. You can use a switch case or a map to manually map enum values to strings.

What's the Difference Between Regular Enums and Enum Classes in C++?

Regular enums are implicitly convertible to integers and can cause name clashes. Enum classes (scoped enums) provide better type safety and scope control, preventing these issues.

Conclusion

In conclusion, Enumeration in C++ are a powerful tool for developers, enhancing code readability and maintainability. Whether it's for representing a set of related constants, combining flags, or ensuring type safety, enums offer a way to make your code more organized and intuitive. Through the examples and discussions provided, you should now have a solid understanding of how to use enums effectively in your C++ projects. Keep experimenting with these concepts in your coding journey to truly master their potential.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass