Printing name of #define by its value?

c, c-preprocessor, macros

Solution

In short, no. The easiest way to do this would be something like so (PLEASE NOTE: this assumes that you can never have an error assigned to zero/null):

 //Should really be wrapping numerical definitions in parentheses. 
#define FILE_NOT_FOUND  (-2)
#define FILE_INVALID    (-3) 
#define INTERNAL_ERROR  (-4)

typdef struct {
  int errorCode;
  const char* errorString;
} errorType;

const errorType[] = {
  {FILE_NOT_FOUND, "FILE_NOT_FOUND" },
  {FILE_INVALID,   "FILE_INVALID"   },
  {INTERNAL_ERROR, "INTERNAL_ERROR" },
  {NULL,           "NULL"           },
};

// Now we just need a function to perform a simple search
int errorIndex(int errorValue) {
  int i;
  bool found = false;
  for(i=0; errorType[i] != NULL; i++) {
    if(errorType[i].errorCode == errorValue) {
      //Found the correct error index value
      found = true;
      break;
    }
  }
  if(found) {
    printf("Error number: %d (%s) found at index %d",errorType[i].errorCode, errorType[i].errorString, i);
  } else {
    printf("Invalid error code provided!");
  }
  if(found) {
    return i;
  } else {
    return -1;
  }
}

Enjoy!

Additionally, if you wanted to save on typing even more, you could use a preprocessor macro to make it even neater:

#define NEW_ERROR_TYPE(ERR) {ERR, #ERR}
 const errorType[] = {
      NEW_ERROR_TYPE(FILE_NOT_FOUND),
      NEW_ERROR_TYPE(FILE_INVALID),
      NEW_ERROR_TYPE(INTERNAL_ERROR),
      NEW_ERROR_TYPE(NULL)
    };

Now you only have to type the macro name once, reducing the chance of typos.

Problem

I have a C program with some definitions for error codes. Like this: ``` #define FILE_NOT_FOUND -2 #define FILE_INVALID -3 #define INTERNAL_ERROR -4 #define ... #define ... ``` Is it possible to print the name of the definition by its value? Like this: ``` PRINT_NAME(-2); // output FILE_NOT_FOUND ```

Original source

Related problems