Enum (C++)

https://en.cppreference.com/w/cpp/language/enum If the first enumerator does not have an initializer, the associated value is zero.

For any other enumerator whose definition does not have an initializer, the associated value is the value of the previous enumerator plus one.

For example,

enum Color { a, b, c = 10, d, e = 1, f, g = f + c };
//a = 0, b = 1, c = 10, d = 11, e = 1, f = 2, g = 12

The variables a, b, …, are now defined in the Color Namespace

Color f = a;
if (f == a) { // equivalent to f == 0
	cout << "variable f is a" << endl;
}

If you redefine the variable a for example, in the global scope, you will get this sort of behavior:

enum Colors {a, b, c = 1, d};
 
int a = 5;
 
int main() {
    std::cout << a << std::endl;  // This will print the value of the integer variable `a`, which is 5
    std::cout << Colors::a << std::endl;  // This will print the value of the enum constant `a`, which is 0
 
    return 0;
}

Enum Compiler Optimization

Kajanan was explaining this to me, there are 2 ways that the compiler can interpret the enum, either use:

  1. Jump Table (fast)
  2. If-else jumps (slow)

This is the compiler optimized way, which creates a jump table