Why do people use enums in C++ as constants when they can use const
?
Enums are lists of constants. When you need a predefined list of values which do represent some kind of numeric or textual data, you should use an enum. You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values.
The use of an enumeration constant (enum) has many advantages over using the traditional symbolic constant style of #define. These advantages include a lower maintenance requirement, improved program readability, and better debugging capability.
Enums are strongly-typed constants that make the code more readable and less prone to errors. It is useful when you have a set of values that are functionally significant and unchanged. An enumeration is a user-defined data type consisting of integral constants and each integral constant is given a name.
No, enum is a type that defines named values, a constant variable or value can be any type. You use an enum variable to hold a value of the enum type, you use a const to define a variable that cannot change and whose value is known at compile time.
Bruce Eckel gives a reason in Thinking in C++:
In older versions of C++,
static const
was not supported inside classes. This meant thatconst
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 untaggedenum
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With