iwin iwin - 5 months ago 40
C++ Question

Using Enum to store numerical constants

I recently came across code which was similar to the following:

#include <stdio.h>

class Example {
enum {
BufSize = 4096,
MsgSize = 200 * 1024,
HeaderFieldLen = 16
int getBufSize() {
return BufSize;

int main() {
Example ex;
printf("%d\n", ex.getBufSize());
return 0;

A class was essentially storing constants in an enum and using their values in its member functions.

Is this a valid use of an enum and if so, is there any reason to store constants in this way, as opposed to in a
or as regular
class member variables?


There are several ways of naming numerical constants in order to avoid magic numbers. Using enumerators are one of them.

The advantage of this method over regular const variables is that enumerators are not variables. Therefore, they are not stored as variables during run-time, they are simply used by the compiler, at compile-time.

[from the comments]
So this usage would be in some ways similar to using preprocessor macros to define constants?

The downside of macros is (mainly) type safety. Macros have no type, so the compiler cannot check for you whether the types match where you use them. Also, while macros are used in C, they are very rarely used in C++ because we have better tools at our disposal.

In C++11, a better way to name these constants is to use constexpr members.

constexpr int BufSize = 4096;
constexpr int MsgSize = 200 * 1024;
constexpr int HeaderFieldLen = 16;

The above code replaces the following.

enum {
    BufSize = 4096,
    MsgSize = 200 * 1024,
    HeaderFieldLen = 16