Is there a one-liner that lets me output the current value of an enum?
Get the value of an Enum To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.
We can convert an enum to string by calling the ToString() method of an Enum.
By default, when you print an enum constant, it prints its literal value e.g. if the name of the enum instance is RED, then it will print RED. This is also the value that is returned by the name() method of java. lang. Enum class.
To get all enum values as an array, pass the enum to the Object. values() method, e.g. const values = Object. values(StringEnum) .
As a string, no. As an integer, %d.
Unless you count:
static char* enumStrings[] = { /* filler 0's to get to the first value, */ "enum0", "enum1", /* filler for hole in the middle: ,0 */ "enum2", "enum3", .... }; ... printf("The value is %s\n", enumStrings[thevalue]);
This won't work for something like an enum of bit masks. At that point, you need a hash table or some other more elaborate data structure.
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