Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I display the value of an enum with printf()?

Tags:

c

enums

printf

Is there a one-liner that lets me output the current value of an enum?

like image 215
Pieter Avatar asked Jan 29 '10 12:01

Pieter


People also ask

How do you read the 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.

How do I display enum as string?

We can convert an enum to string by calling the ToString() method of an Enum.

What happens when you print 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.

How do you find the value of an enum in an array?

To get all enum values as an array, pass the enum to the Object. values() method, e.g. const values = Object. values(StringEnum) .


1 Answers

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.

like image 93
bmargulies Avatar answered Sep 23 '22 05:09

bmargulies