C++ – Why do people use enums in C++ as constants while they can use const


Why do people use enums in C++ as constants when they can use const?

Best Solution

Bruce Eckel gives a reason in Thinking in C++:

In older versions of C++, static const was not supported inside classes. This meant that const was useless for constant expressions inside classes. However, people still wanted to do this so a typical solution (usually referred to as the “enum hack”) was to use an untagged enum with no instances. An enumeration must have all its values established at compile time, it’s local to the class, and its values are available for constant expressions. Thus, you will commonly see:

#include <iostream>
using namespace std;

class Bunch {
  enum { size = 1000 };
  int i[size];

int main() {
  cout << "sizeof(Bunch) = " << sizeof(Bunch) 
       << ", sizeof(i[1000]) = " 
      << sizeof(int[1000]) << endl;