Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type-casting enum to integer and vice versa [closed]

Tags:

c++

enums

casting

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

like image 729
ontherocks Avatar asked Dec 24 '13 14:12

ontherocks


1 Answers

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.

like image 166
Violet Giraffe Avatar answered Oct 11 '22 18:10

Violet Giraffe