Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 880
eonil Avatar asked Mar 12 '11 06:03

eonil


People also ask

Can you cast an enum in C?

Yes. In C enum types are just int s under the covers. Typecast them to whatever you want. enums are not always ints in C.

Can we assign one enum to another?

enum types are integer types and you are allowed to assign any integer value to any integer object. This is valid and no diagnostic is required by the Standard. Nevertheless some implementations warn when you try to mix up different enum types.

Can we have enum inside enum in C?

It is not possible to have enum of enums, but you could represent your data by having the type and cause separately either as part of a struct or allocating certain bits for each of the fields.


1 Answers

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).
like image 102
Carl Norum Avatar answered Sep 30 '22 01:09

Carl Norum