Is there any potential problem when casting an int to enum when the int is greater than the number of possible values?

Is there any potential problem that I should be aware of when casting an int to enum when the int is greater than the number of possible values, say

Here is the code snippet, which seems work well:) :

#include <iostream>
 
 int main()
 {
     enum Demo{NONE=0, OK, HEART, OTHERS, FULL}; 
     enum Demo demo = static_cast<enum Demo>(9);

     std::cout << static_cast<int>(demo) << std::endl;
     std::cout << (static_cast<int>(demo) == 9) << std::endl;
 }

  • 2

    Yes, you risk UB, unless you explicitly specify the underlying type of the enum, or use enum class (which defaults to : int underlying type, unlike enum). Cppreference explains it

    – 

  • Do you include “Is unequal to all the enumerators” in “potencial problem”?

    – 

  • the number of possible values is not restricted by the enumerators but by the underlying type. The only problem to be aware of is wrong expectations 😉 because the range of Demo is much more than what you think it is

    – 

  • 1

    @463035818_is_not_an_ai The valid values of Demo are 0,1,2,3,4,5,6,7, despite its underlying type being int.

    – 

  • C++ enum is free to use underlying type that fits all enumerators. OTOH as value 9 has to fit into smallest integral type char, it looks OK.

    – 

Leave a Comment