Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can do it with a bit of macro magic:</p> <pre><code>#define FRUITS \ etype(Unknown), \ etype(Apple), \ etype(Orange), \ etype(Banana), \ etype(Apricot), \ etype(Mango) #define etype(x) F_##x typedef enum { FRUITS } Fruit; #undef etype #define etype(x) #x static const char *strFruit[] = { FRUITS }; </code></pre> <p>Here is a test program:</p> <pre><code>#include &lt;iostream&gt; #include &lt;exception&gt; #include &lt;vector&gt; #define FRUITS \ etype(Unknown), \ etype(Apple), \ etype(Orange), \ etype(Banana), \ etype(Apricot), \ etype(Mango) #define etype(x) F_##x typedef enum { FRUITS } Fruit; #undef etype #define etype(x) #x static const char *strFruit[] = { FRUITS }; const char *enum2str (Fruit f) { return strFruit[static_cast&lt;int&gt;(f)]; } Fruit str2enum (const char *f) { const int n = sizeof(strFruit) / sizeof(strFruit[0]); for (int i = 0; i &lt; n; ++i) { if (strcmp(strFruit[i], f) == 0) return (Fruit) i; } return F_Unknown; } int main (int argc, char *argv[]) { std::cout &lt;&lt; "I like " &lt;&lt; enum2str(F_Mango) &lt;&lt; std::endl; std::cout &lt;&lt; "I do not like " &lt;&lt; enum2str(F_Banana) &lt;&lt; std::endl; std::vector&lt;char *&gt; v; v.push_back("Apple"); v.push_back("Mango"); v.push_back("Tomato"); for (int i = 0; i &lt; v.size(); ++i) { const Fruit f = str2enum(v[i]); if (f == F_Unknown) std::cout &lt;&lt; "Is " &lt;&lt; v[i] &lt;&lt; " a fruit?" &lt;&lt; std::endl; else std::cout &lt;&lt; v[i] &lt;&lt; " is a fruit" &lt;&lt; std::endl; } return 0; } </code></pre> <p>It outputs:</p> <pre><code>I like Mango I do not like Banana Apple is a fruit Mango is a fruit Is Tomato a fruit? </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload