I learned enums when I learned C and from time to time I keep myself reminding about it and most of the time by re-reading from some source,it occurred to me that this is d
I use them as parameters to functions as opposed to using booleans to improve readability of my code.
with all said about using enums as symbolic constant, I'd like to emphasize that in C++ using enum in a class gives a very nice, readable and convenient way of encapsulating and exposing class's capabilities, e.g.
class BlockCipher {
public:
enum PaddingOptions { NO_PADDING, DEFAULT_PADDING, ZERO_PADDING /*...*/ }
void encrypt(const std::string& cleartext, std::string& ciphertext,
PaddingOptions pad=DEFAULT_PADDING);
};
int main()
{
std::string clear("hello, world");
std::string encrypted;
BlockCipher encryptor;
encryptor.encrypt(clear, encrypted, BlockCipher::NO_PADDING);
}
One use of enums is to make code clearer at the call site. Compare:
//Usage: Kick(Dog);
enum PetType
{
Cat,
Dog
};
void Kick(PetType p)
{
switch(p)
{
case Cat:
//Kick Cat
break;
case Dog:
//Kick Dog
break;
default:
//Throw an exception.
break;
}
}
//Usage: Kick(false);
void Kick(bool isCat)
{
if (isCat)
{
//Kick Cat
}
else
{
//Kick Dog
}
}
Even though a boolean would work just as well, someone unfamiliar with the function will need to work much harder to determine what it does in the case that a boolean was used. Kick(Dog)
is much clearer than Kick(false)
.
enum
s can make code easier to read and may present better type checking during compilation.
int
or
unsigned int
and assigned into
those kind of variables, thus
creating a hole in the type checking
benefit.enum
to
std::cout
results in the enum
converted to an integer then printed
out. Most implementations must
perform a table lookup to convert
the enum
to text before printing.Another alternative to enum
is to use a string. I've worked at shops where they pass a constant string instead of an enum. One advantage is that the named value is always available, even when debug symbols are not. Also there are no conversions required when printing.
switch
statement.Take a look at the rationale about enum at Wikipedia.
Worth mentioning too: Enumerated Types - enums
Enums have one advantage over #define
, but it's purely an implementation detail: debuggers typically can show/use enum
values but #define
d values.
On the other hand, #define
has several fundamental advantages, one of which is that you can test for the existence with #ifdef
. This is useful if you need to support multiple versions of a library, and want to optionally use new enum-like choices if they're available.
Some library authors use a hybrid approach of first defining the constants with enum
then:
#define FOO FOO
#define BAR BAR
etc.