Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static const Member Value vs. Member enum : Which Method is Better & Why?

If you want to associate some constant value with a class, here are two ways to accomplish the same goal:

class Foo { public:     static const size_t Life = 42; };  class Bar { public:     enum {Life = 42}; }; 

Syntactically and semantically they appear to be identical from the client's point of view:

size_t fooLife = Foo::Life; size_t barLife = Bar::Life; 

Is there any reason other than just pure style concerns why one would be preferable to another?

like image 927
John Dibling Avatar asked Oct 15 '08 14:10

John Dibling


People also ask

Which is better const or enum?

Enums limit you to the required set of inputs whereas even if you use constant strings you still can use other String not part of your logic. This helps you to not make a mistake, to enter something out of the domain, while entering data and also improves the program readability.

Which is better #define or enum?

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.

Can static variables be declared as const?

“static const” is basically a combination of static(a storage specifier) and const(a type qualifier). The static determines the lifetime and visibility/accessibility of the variable.

Why is const better than #define?

The big advantage of const over #define is type checking. #defines can't be type checked, so this can cause problems when trying to determine the data type. If the variable is, instead, a constant then we can grab the type of the data that is stored in that constant variable.


1 Answers

The enum hack used to be necessary because many compilers didn't support in-place initialization of the value. Since this is no longer an issue, go for the other option. Modern compilers are also capable of optimizing this constant so that no storage space is required for it.

The only reason for not using the static const variant is if you want to forbid taking the address of the value: you can't take an address of an enum value while you can take the address of a constant (and this would prompt the compiler to reserve space for the value after all, but only if its address is really taken).

Additionally, the taking of the address will yield a link-time error unless the constant is explicitly defined as well. Notice that it can still be initialized at the site of declaration:

struct foo {     static int const bar = 42; // Declaration, initialization. };  int const foo::bar; // Definition. 
like image 62
Konrad Rudolph Avatar answered Sep 28 '22 02:09

Konrad Rudolph