I have learnt that enums are data types as opposed to data structures. I have also learnt that usually they are nominal in nature rather than ordinal. Consequentially, it does not make sense to iterate through an enum, or obtain the enum's constant value like you would an array, e.g. week[3]
.
However, I have come across instances where an index is used to obtain the value from an enum:
#include <iostream>
enum week {Mon=5, Tues, Wed};
int main()
{
week day = (week)0;
std::cout << day << "\n"; // outputs 0
day = (week)13;
std::cout << day << "\n"; // outputs 13
return 0;
}
How is this working?
I assumed (week)13
would not work, given there is nothing at this index. Is it that the cast is failing and falling back to the type to be cast?
As a side note: I believe some confusion with this style of code in C/C++ may occur due to other languages (C#) handling this case differently.
Edit: The linked solutions don't answer the question I'm asking. 1 is about comparing integers to enums -- in this case I'm asking why casting an int to an enum gives a certain result.[2] (Assigning an int value to enum and vice versa in C++) mentions "Old enums (unscoped enums) can be converted to integer but the other way is not possible (implicitly). ", but by the accounts of my code, it does seem possible. Lastly 3 has nothing to do with this question: I'm not talking about assignment of enums, rather the casting of them via an integer.