开发者

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

开发者 https://www.devze.com 2022-12-24 12:04 出处:网络
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:

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 开发者_如何学Pythonthis way, rather than just "You can't do that"


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.


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.


The compiler does not know how to implicitly convert one enumerated data type to another.

Try the following.

enum typeX { one } x;
enum typeY { two } y;
x = (typeX) y;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号