Concepts and use of enum

An enum gives readable names to a fixed set of integer constants, so code says MEAL instead of the mystery number 1.

8 min read · 10 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

What does category 1 mean?

Six months after writing the till, you read your own code:

if (item.category == 1) { applyMealDiscount(); }

Is 1 a meal? A drink? You scroll for twenty minutes to find out. Meanwhile a teammate stores category = 7, a category that does not exist, and the compiler happily agrees.

Magic numbers rot programs. C++ has a small tool built exactly for this: give the numbers names, and give the set a type.

Theory

The menu board's fixed sections

The canteen's menu board has exactly three sections: Snacks, Meals, Drinks. No dish is ever pinned outside a section, and nobody invents a fourth section on a whim.

An enum is that board inside your program: a closed list of named options. Any item must sit in one of them, and everyone reads section names, not section numbers.

Theory

Enumeration, formally

An enum (enumeration) is a user-defined type whose values are named integer constants:

enum Category { SNACK, MEAL, DRINK };

By default the names number from 0: SNACK is 0, MEAL is 1, DRINK is 2.

Declare and use a variable of the type:

Category c = MEAL;

Now c can meaningfully hold only members of the list, and if (c == MEAL) reads like English.

Practical

The till's categories, named at last

#include <iostream>
using namespace std;

enum Category { SNACK, MEAL, DRINK };        // 0, 1, 2
enum Tier { REGULAR = 1, MEMBER = 5, STAFF = 10 };  // custom values

int main() {
    Category c = MEAL;

    if (c == MEAL)
        cout << "Thali section" << endl;

    cout << c << endl;        // prints 1, the underlying integer
    cout << STAFF << endl;    // prints 10

    switch (c) {              // enums shine in switch
        case SNACK: cout << "snack"; break;
        case MEAL:  cout << "meal";  break;
        case DRINK: cout << "drink"; break;
    }
    return 0;
}

Theory

Custom values and the continuation rule

You may assign values yourself: enum Tier { REGULAR = 1, MEMBER = 5, STAFF = 10 };

If you assign some and skip others, an unassigned name takes previous value + 1:

enum Code { A = 100, B, C = 200, D };

gives B = 101 and D = 201.

Why bother with custom values? To match external facts: error codes, discount percentages, keyboard codes, anything where the number itself carries meaning.

Think first

Predict the output

With enum Category { SNACK, MEAL, DRINK }; the till runs:

Category c = DRINK;

cout << c;

Before tapping: what exactly appears on screen?

Show the answer

2, not the word DRINK. An enum name is a costume over an integer: cout strips the costume and prints the number (SNACK 0, MEAL 1, DRINK 2). If you want the word on screen you must translate it yourself, typically with a switch or an array of strings. Expecting the name to print is the single most common enum surprise.

Quiz

Given enum Code { A = 100, B, C = 200, D }; what are the values of B and D?

  1. B = 101, D = 201
  2. B = 0, D = 1
  3. B = 100, D = 200
  4. B = 200, D = 300
Show the answer

B = 101, D = 201

The continuation rule: an unassigned name is previous + 1. B follows A(100) so B is 101; D follows C(200) so D is 201. Option B applies the default-from-zero rule, but that only holds when NO values are assigned. Options C and D invent copying and jumping rules that enums do not have.

Watch out

The looseness to know about

Classic enums convert to int silently, so nonsense like MEAL + DRINK compiles (it is just 1 + 2). The type protects reading, not arithmetic.

Modern C++ (C++11) added enum class: enum class Category { SNACK, MEAL }; requires Category::MEAL and refuses silent conversion. If an exam asks how to make enums type-safe, that is the answer. For this syllabus, master the classic enum first.

Theory

Where it fits in your class designs

Enums are the third member of the user-defined family alongside class and struct. In the Item class from the previous lesson, Category category; as a member variable is cleaner than an int and documents itself. You will meet the same idea everywhere: HTTP status groups, weekdays, states of a game, semester numbers.

Summary

Key takeaways

  • enum Name { A, B, C }; creates a user-defined type of named integer constants.
  • Default numbering starts at 0; custom values allowed; unassigned names take previous + 1.
  • cout prints the underlying integer, never the name.
  • Classic enums convert to int silently; enum class (C++11) is the strict version.
  • Use enums for closed sets: categories, tiers, states; they read well in switch.
  • Memory hook: the menu board's fixed sections.

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Data Encapsulation and inheritance

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

Concepts and use of enum · Object Oriented Programming and Data Structures (OOPs & D.S.) · Gri-Learn