Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 651
Loai Abdelhalim Avatar asked May 22 '09 20:05

Loai Abdelhalim


People also ask

Why is enum better than constant?

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.

What is the benefit of using enum to declare a constant in C?

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.

Should enums be constants?

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.

What is the difference between enum and constant in C?

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.


1 Answers

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; } 
like image 186
Bastien Léonard Avatar answered Oct 11 '22 14:10

Bastien Léonard