[英]associating enums with strings in C
我看過這個鏈接
我在客戶端提供的庫頭文件中以下列方式定義了一系列enums
(我無法更改):
枚舉也很稀疏。
typedef enum
{
ERROR_NONE=59,
ERROR_A=65,
ERROR_B=67
}
我想在我的函數中打印這些值,例如我想打印ERROR_NONE
而不是59
。 是否有更好的方法只使用switch
case
或if else
構造來完成這項工作? 例
int Status=0;
/* some processing in library where Status changes to 59 */
printf("Status = %d\n",Status); /* want to print ERROR_NONE instead of 59 */
直接應用字符串化運算符可能會有所幫助
#define stringize(x) #x
printf("%s\n", stringize(ERROR_NONE));
您已經提到過您無法更改庫文件。 如果你決定:),你可以使用如下的X
宏
enumstring.c
#include <stdio.h>
#define NAMES C(RED)C(GREEN)C(BLUE)
#define C(x) x,
enum color { NAMES TOP };
#undef C
#define C(x) #x,
const char * const color_name[] = { NAMES };
int main( void )
{ printf( "The color is %s.\n", color_name[ RED ]);
printf( "There are %d colors.\n", TOP ); }
stdout
The color is RED.
There are 3 colors.
在這里閱讀更多
編輯 :通過你向我們展示的具體例子,我擔心, switch-case
是你能得到的最接近的,特別是當你有稀疏的enums
。
常見問題11.17 。 使用xstr()
宏。 你可能應該使用它:
#define str(x) #x
#define xstr(x) str(x)
printf("%s\n", xstr(ERROR_A));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.