Reputation: 1161
I thought enums were static, what's the point of a const enum
?
For example:
const typedef enum
{
NORMAL_FUN = 1,
GREAT_FUN = 2,
TERRIBLE_FUN = 3,
} Annoying;
I have had an old program dropped on my head that I am being forced to work with (from an equipment manufacturer), and I keep coming across enums being defined with const typedef enum
.
Now, I am used to C#, so I don't fully understand all the C++ trickery that goes on, but this case appears to be straightforward.
From the coding of the program it would appear that variables that are of type Annoying
are meant to be changed, everywhere, all the time.
They aren't meant to be constant. Long story short, the compiler doesn't like it.
This sample was written back sometime prior to 2010, so this could be some kind of version difference, but what did/does const typedef enum
even mean?
Upvotes: 0
Views: 687
Reputation: 234635
Writing
typedef enum
{
NORMAL_FUN = 1,
GREAT_FUN = 2,
TERRIBLE_FUN = 3,
} Annoying;
has the advantage of the enum
working nicely in C too, which handles typedef
by introducing Annoying
into the typedef namespace. So the provider of the enum
declaration could be also targetting C.
Using the const
qualifier means that you cannot write code like
Annoying foo = NORMAL_FUN;
foo = GREAT_FUN; // this will fail as `foo` is a `const` type.
Upvotes: 1
Reputation:
const typedef Type def;
and typedef const Type def;
mean the same thing, and have for many years. There's nothing special about the case where Type
is an enum
definition, and you can see it too in:
const typedef int const_int;
const_int i = 3;
i = 4; // error
Upvotes: 3
Reputation: 409136
That makes the type-alias Annoying
constant, so all variables declared with that type-aliases are constant:
Annoying a = NORMAL_FUN;
a = GREAT_FUN; // Failure, trying to change a constant variable
Upvotes: 7