This is a basic question which I hoped to Google easily, but didn't find an answer for.
Let's say that I have an enum:
enum abc { a, b, c };
What are the supported implicit conversions? Are there any compiler extensions or different behavior between compilers?
I'm asking about implicit conversion to an enum:
enum abc test = (** which type can appear here? **);
As well as implicit conversion from an enum:
(** which type can appear here? **) test2 = test;
I'd like to know the answer for both C and C++.
For the compiler it is ok. Although you might want to familiarize yourself with C++11, which allows the definition of enums that are not int-based. For good coding, it is not "ok", however: casting is almost always used as a cure for a bad choice of variable, function argument or function return type.
An implicit conversion sequence is the sequence of conversions required to convert an argument in a function call to the type of the corresponding parameter in a function declaration. The compiler tries to determine an implicit conversion sequence for each argument.
In C enum types are just int s under the covers. Typecast them to whatever you want. enums are not always ints in C. However, it is reasonable to assume they are built on integral types.
Implicit conversions allow the compiler to treat values of a type as values of another type. There's at least one set of scenarios in which this is unambiguously bad: non-total conversions. That is, converting an A to a B when there exists A s for which this conversion is impossible.
As the reference says:
Values of unscoped enumeration type are implicitly-convertible to integral types
Reference link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With