Am Donnerstag, dem 30.04.2026 um 16:14 +0200 schrieb Jakub Jelinek via Gcc:
> On Thu, Apr 30, 2026 at 04:54:02PM +0300, Yair Lenga wrote:
> > Thanks for taking the time.
> > My focus is on the C compiler. Assuming the enum "metadata" is stored
> > in a structure/variables that are readable by the program - can C
> > programs access it ? Does it apply to "C" enums, or only to "C++" enum
> > classes.
>
> Any kind of enum.
> It is roughly
> #include <meta>
>
> template <typename E>
> constexpr const char *
> enum_to_string (E v)
> {
> template for (constexpr auto e : std::define_static_array (enumerators_of
> (^^E)))
> if (v == [:e:])
> return std::define_static_string (identifier_of (e));
> return nullptr;
> }
>
> example of how it can be used:
> enum E { F, G, H } i;
>
> int
> main ()
> {
> const char *f = enum_to_string (F);
> const char *g = enum_to_string (G);
> const char *h = enum_to_string (H);
> const char *j = enum_to_string (i);
> }
> Of course, if compiled with C++26 for use in C, one would need to
> wrap it in a wrapper, one per enum so that C can use it.
> Also, note the above function when not evaluated at compile time doesn't
> have a switch but a series of ifs, but e.g. GCC when optimizing ought to
> transform that into a switch and later perhaps into an array access or
> whatever is appropriate based on how dense the enumerals in the enumeration
> type are, how many etc.
>
> Jakub
BTW: I often felt the need for a type-to-string serialization
builtin in C. This would be incredible useful for many things.
Martin