Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning an int value to enum and vice versa in C++

Tags:

c++

#include <iostream>    

typedef enum my_time {
  day,
  night
} my_time;

int main(){    
  // my_time t1 = 1; <-- will not compile
  int  t2 = night;
  return 0;  
} 

How is it expected that I can assign an enum value to an int but not the other way in C++?

Of course this is all doable in C.

like image 451
Dan Avatar asked Sep 04 '25 16:09

Dan


2 Answers

Implicit conversions, or conversions in general, are not mutual. Just because a type A can be converted to a type B does not imply that B can be converted to A.

Old enums (unscoped enums) can be converted to integer but the other way is not possible (implicitly). Thats just how it is defined. See here for details: https://en.cppreference.com/w/cpp/language/enum

Consider that roughly speaking enums are just named constants and for a function

void foo(my_time x);

It is most likely an error to pass an arbitrary int. However, a

void bar(int x);

can use an enum for special values of x while others are still allowed:

 enum bar_parameter { NONE, ONE, MORE, EVEN_MORE, SOME_OTHER_NAME };
 bar(NONE);
 bar(SOME_OTHER_NAME);
 bar(42);

This has been "fixed" in C++11 with scoped enums that don't implicitly convert either way.

like image 146
463035818_is_not_a_number Avatar answered Sep 07 '25 16:09

463035818_is_not_a_number


  You could cast to int. This expression makes an explicit conversion of the specified data type (int) and the given value (night).

 int t2 = static_cast<int>(night)
like image 35
user11717481 Avatar answered Sep 07 '25 18:09

user11717481



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!