Possible to convert list of #defines into strings

前端 未结 8 1349
梦谈多话
梦谈多话 2021-02-05 22:45

Suppose I have a list of #defines in a header file for an external library. These #defines represent error codes returned from functions. I want to wri

8条回答
  •  南旧
    南旧 (楼主)
    2021-02-05 23:27

    Another way to do it that's popular in generated code is:

    #define NO_ERROR 0
    #define ONE_KIND_OF_ERROR 1
    #define ANOTHER_KIND_OF_ERROR 2
    static const char* const error_names[] = {"NO_ERROR", "ONE_KIND_OF_ERROR", "ANOTHER_KIND_OF_ERROR"};
    
    const char* convertToString(int errorCode) {return error_names[errorCode];}
    

    I prefer the switch case way I already mentioned, but depending on how your code is structured it might be easier as part of your build process to generate that array automatically

提交回复
热议问题