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

Loai Nagati picture Loai Nagati · May 22, 2009 · Viewed 31.7k times · Source

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

Answer

Bastien Léonard picture Bastien Léonard · May 22, 2009

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;
}

[Edit]

I think it would be more fair to link Bruce Eckel's site: http://www.mindview.net/Books/TICPP/ThinkingInCPP2e.html.