Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit conversion to/from an enum

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++.

like image 543
Paul Avatar asked Dec 01 '16 21:12

Paul


People also ask

Can you cast an enum class to int?

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.

What is an implicit conversion?

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.

Can enum be Typecasted?

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.

Is implicit type conversion bad?

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.


1 Answers

As the reference says:

Values of unscoped enumeration type are implicitly-convertible to integral types

Reference link

like image 91
Piotr Pilip Avatar answered Oct 19 '22 17:10

Piotr Pilip