[Tutor] enumeration in C++
alan.gauld@bt.com
alan.gauld@bt.com
Wed, 3 Apr 2002 13:42:30 +0100
> What's enumeration good for?
> but never found out its purpose.
One thing I use it for extensively is creating unique error codes:
enum errorcodes = {
CriticalError = 1,
LessCritical,
Warning,
BadInput,
BadOutput,
BadUser,
BadDog,
}
Now the codes are automatically given unique values starting at 1.
I could achieve the same with #defines:
#define CriticalError 1
# define LessCritical CriticalError + 1
etc....
#define BadDog BadUser+1
But when the compiler tries to grok those it expands the
values so that the last one actually looks like 1+1+1+1+1+1....+1
Hopefully the optimiser will do the arithmetic but its still ugly.
Also by using an enum we get typechecking and flagging of
invalid names(spelling mistakes etc)
There are a bunch of other things too, but C/C++ enums are not
as well behaved as, say Pascal, where defining an enum limits
the range. In C you can hard code an invalid value to a
variable holding an enum because C treats it pretty much
like any other int!
HTH,
Alan g.