按其值打印#define的名称?

Ant*_*rst 6 c macros c-preprocessor

我有一个C程序,其中包含一些错误代码的定义.像这样:

#define FILE_NOT_FOUND -2
#define FILE_INVALID -3 
#define INTERNAL_ERROR -4
#define ... 
#define ... 
Run Code Online (Sandbox Code Playgroud)

是否可以按其值打印定义的名称?像这样:

PRINT_NAME(-2);

// output
FILE_NOT_FOUND
Run Code Online (Sandbox Code Playgroud)

Clo*_*oud 6

简而言之,没有.最简单的方法就是这样(请注意:这假设您永远不会将错误分配给零/ 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;
  }
}
Run Code Online (Sandbox Code Playgroud)

请享用!

此外,如果您想节省更多的输入,可以使用预处理器宏使其更整洁:

#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)
    };
Run Code Online (Sandbox Code Playgroud)

现在您只需输入一次宏名称,减少拼写错误的可能性.


Ric*_*dle 2

不,那不可能。这会打印什么?

#define FILE_NOT_FOUND   1
#define UNIT_COST        1
#define EGGS_PER_RATCHET 1

PRINT_NAME(1);
Run Code Online (Sandbox Code Playgroud)