Why can I set an anonymous enum equal to another in C but not C++?
c, c++, compiler-construction
Solution
Converting from one enum type to another goes via an integer type (probably the underlying type of the source, not sure).
An implicit conversion from enum to an integer type is allowed in both C and C++. An implicit conversion from an integer type to enum is allowed in C, but not in C++.
Basically, C++ is being more type safe. It's trying to stop you doing this:
enum {zero, one, two} x;
x = 143; // assigns a value outside the range of the enum
If you want to perform this enum-enum conversion in C++, you could use typeof/declspec/boost typeof or equivalent. In GCC:
int main() {
enum {zero, one, two} x;
enum {zero1, one1, two1} y = two1;
typedef typeof(x) xtype;
x = static_cast<typeof(x)>(y);
}
It doesn't normally make sense to do so, though. For most purposes, enums (and especially anonymous ones) are "enumerated types". They do just happen to be "implemented" by the C and C++ standards as integers wearing funny hats, but that doesn't mean that `red` is "equal to" `hammer` just because they each appear first in two different enums (colours and tools respectively). `static_cast` suggests that there's a relation between the two types involved. Any two enum types are "related" by the fact that both have an underlying integer type, and those are related, so the "relation" there really doesn't say much. If you write this code you're getting a pretty poor version of type safety.
Problem
I have the following code snippet: ``` enum { one } x; enum { two } y; x = y; ``` That will compile in C, but in C++, I get the following error: ``` test.c:6: error: cannot convert ‘main()::<anonymous enum>’ to ‘main()::<anonymous enum>’ in assignment ``` Can someone explain to me why this is happening? I would prefer an answer with some specifics about why the compiler behaves this way, rather than just "You can't do that"