Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I set an anonymous enum equal to another in C but not C++?

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"

like image 582
samoz Avatar asked Mar 18 '10 23:03

samoz


2 Answers

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.

like image 154
Steve Jessop Avatar answered Sep 29 '22 04:09

Steve Jessop


My guess is that this is due to the stricter typing in C++.

In C x = 5; also compiles. In C++ it won't because there is no type conversion defined. That's the same reason why x = y does not compile.

You can have a look at this example on codepad, which gives a more detailed error description than your compiler.

like image 44
foraidt Avatar answered Sep 29 '22 05:09

foraidt