I have an enum
enum MYENUM
{
VAL_1 = 0,
VAL_2,
VAL_3
};
and two functions that have integer and enum as parameters respectively
void MyIntegerFunction(int integerValue)
{
...
}
void MyEnumFUnction(MYENUM enumValue)
{
...
}
I have two variables
int intVar = 10;
MYENUM enumVar = VAL_2;
In which of the two cases below is it correct to do a typecasting while calling these functions and why?
Case#1. MyEnumFUnction(static_cast<MYENUM>(intVar));
Case#2. MyIntegerFunction(static_cast<int>(enumVar));
PS: No C++11
enum
to int
is unambiguous cast (assuming C++ 03 where enum
is basically an int
), will be performed implicitly no problem. int
to enum
is potentially errorneous as it's a narrowing cast, not every int
value is a valid enum
value. That's why casting int
to enum
is only possible explicitly.
Same holds for C++ 11 and later standards, with the exception that C++ 11 introduced strongly typed enums and specific size enums.
Strongly typed enum is declared enum class
instead of just enum
, and it cannot be converted to an integer nor any other type, save for a user-defined conversion operator or function, or brute force (static_cast
). Sized enums are declared like this: enum Colors : char {...}
. This particular enum's values will have char
type instead of the default int
.
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