Can a C program determine a macro identifier/enum name based on its value?

c, enums, macros

Solution

Not directly, as pointed out by others those identifiers are not available at runtime, but you can use a parallel list of names (an X Macro can help):

#include <stdio.h>

#define ERRS \
    X(ERR_SUCCESS) \
    X(ERR_BAD_INPUT) \
    X(ERR_MORE)

#define X(x) x,
enum err_t {ERRS};
#undef X

#define X(x) #x,
static char *err_name[] = {ERRS};
#undef X

static int foo(void)
{
    /* ... */
    return ERR_BAD_INPUT;
}

int main(void)
{
    printf("%s\n", err_name[foo()]);
    return 0;
}

Output:

ERR_BAD_INPUT

Problem

Let's say we define some error codes as macros - ``` #define ERR_SUCCESS 0 #define ERR_BAD_INPUT 1 ``` ... or as an enumerated data type - ``` enum err_t = { ERR_SUCCESS, ERR_BAD_INPUT, ...}; ``` and one of these ids is returned by a function such as - ``` int foo(); /* if foo() returns 0, it means success, etc */ ``` Can the caller of `foo()` determine which identifier / name (ERR_SUCCESS, ERR_BAD_INPUT, ...) is linked to the int return value?

Original source

Related problems