Skip to content


C/C++, Enumerations

As it turns out (per written on the K&R book), there are a number of things to watch out for for Enumerations. Some are well known and trivia while some are not. I’m listing them all here for completeness sake, and also with some comments for a few of the points:

  1. Names in enums cannot clash (i.e. names must be distinct across all the enums)
  2. Values in enum do not need to be distinct
  3. First value in a enum default to 0 if unspecified
  4. Any name without a value will auto increment from the previously defined value
  5. Compilers will not check if the value assigned to the enum corresponds to a valid name

Point 1
For point 1, notice that there are a number of valid solutions:

Prefixing the names:

enum Color {cRed, cBlue};
enum Mood {mRed, mYellow};

Classes/Structs:

Stuct ColorStruct { enum Color {Red, Blue} c };
Struct MoodStruct { enum Mood {Red, Yellow} m };

// In C
ColorStruct s;
s.c = cRed;

// In C++
ColorStruct::cRed;

Using namespace:

namespace Color { enum c {Red, Yello}; };

// Usable only in C++
Color::Red
// Or
using namespace Color;
Red;

Notice that this last approach has a problem in large codebases. Since you can use a namespace quite easily anywhere in a program, there is no guarantee that there won’t be a clash from another namespace


Point 2
Somewhat useful if you are trying to deal with multiple enum names the same way in a switch statement for example

#include <stdio.h>

// use typedef enum Color {..} Color; if you dont want to use enum Color varNam
// but want to do Color varName
enum Color {cWhite = 0, cBlack = 0, cGray = 1, cRed = 2, cBlue = 3};

int main() {
    enum Color c = 0;
    // can also use the label such as c = cBlack;

    switch(c) {
        case 0:
            printf("BW");
            break;
        case 1:
            printf("Gray");
            break;
        case 2:
            printf("Red");
            break;
        case 3:
            printf("Blue");
            break;
    }

    return 0;
}

Point 5
For example if you set c = 5 from the code above, there will be no error. The compiler does not check to see if the value you assigned is actually valid.

In this case you will just get no output because the switch doesnt hit anything

Posted in C/C++. Tagged with , , .