简体   繁体   中英

Is valid casting an `enum` to other `enum` in [C]?

I have two enums.

enum A { A1=1, A2=2 }

enum B { B1=1, B2=2 }

Is this valid by standard of C?

A a = A1;
B b = a;

(compiled well with Clang, but I can't sure this is standard or extension behavior)

It's valid by the standard, but the C99 spec mentions that some implementations may generate a warning:

An implementation may generate warnings in many situations, none of which are specified as part of this International Standard. The following are a few of the more common situations.

  • A value is given to an object of an enumerated type other than by assignment of an enumeration constant that is a member of that type, or an enumeration variable that has the same type, or the value of a function that returns the same enumerated type (6.7.2.2).

I believe that in C enums are basically int s with personality. (This contrasts with C++ where they are full fledged types.) So, assigning different enum s is effectively still just working with int s, so it is legal. However, I'm not saying this is recommended :)

It is valid Standard C but it's a bad idea. Note that it is not valid C++.

valid - enums are language features which are intended to help the developer. If you don't specify enum item values their values it's generated automatically. From another language .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM