Is there a reason to use enum to define a single constant in C++ code?
c++, constants, enums
Solution
The reason is mainly brevity. First of all, an `enum` can be anonymous:
class foo {
enum { bar = 1 };
};
This effectively introduces `bar` as an integral constant. Note that the above is shorter than `static const int`.
Also, no-one could possibly write `&bar` if it's an `enum` member. If you do this:
class foo {
static const int bar = 1;
}
and then the client of your class does this:
printf("%p", &foo::bar);
then he will get a compile-time linker error that `foo::bar` is not defined (because, well, as an lvalue, it's not). In practice, with the Standard as it currently stands, anywhere `bar` is used where an integral constant expression is not required (i.e. where it is merely allowed), it requires an out-of-class definition of `foo::bar.` The places where such an expression is required are: `enum` initializers, `case` labels, array size in types (excepting `new[]`), and template arguments of integral types. Thus, using `bar` anywhere else technically requires a definition. See C++ Core Language Active Issue 712 for more info - there are no proposed resolutions as of yet.
In practice, most compilers these days are more lenient about this, and will let you get away with most "common sense" uses of `static const int` variables without requiring a definition. However, the corner cases may differ, however, so many consider it to be better to just use anonymous `enum`, for which everything is crystal clear, and there's no ambiguity at all.
Problem
The typical way to define an integer constant to use inside a function is: ``` const int NumbeOfElements = 10; ``` the same for using within a class: ``` class Class { ... static const int NumberOfElements = 10; }; ``` It can then be used as a fixed-size array bound which means it is known at compile time. Long ago compilers didn't support the latter syntax and that's why enums were used: ``` enum NumberOfElementsEnum { NumberOfElements = 10; } ``` Now with almost every widely used compiler supporting both the in-function `const int` and the in-class `static const int` syntax is there any reason to use the enum for this purpose?