C语言 -- 将枚举(enum)变量里的值同时作为字符串(string)和变量标识符(identifier)

本文介绍了C语言中如何将枚举变量的值同时用作字符串和标识符,强调了在定义枚举变量时的注意事项,并提供了利用宏定义转换的代码示例,展示了运行结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、注意事项

1.由于C语言里定义枚举变量时,如这样enum var_enum {a ,b ,c}
则使用的时候不能直接用 var_enum xx; 而是要enum var_enum xx;
所以下面的代码和引用文章的代码有一点差别。
2.宏定义里#号将记号转化为字符串。
详细可参考:CSDN:#号的作用
3.宏定义里##号表示把两个宏参数贴合在一起.
详细可参考:CSDN:#号和##号的作用

二、代码(1/2)

main.c

#include <stdio.h>
#include <string.h>

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// expansion macro for enum value definition
#define ENUM_VALUE(name,assign) name assign,

// expansion macro for enum to string conversion
#define ENUM_CASE(name,assign) case name: return #name;

// expansion macro for string to enum conversion
#define ENUM_STRCMP(name,assign) if (!strcmp(str,#name)) return name;

/// declare the access function and define enum values
#define DECLARE_ENUM(EnumType,ENUM_DEF) \
  enum EnumType { \
    ENUM_DEF(ENUM_VALUE) \
  }; \
  const char *GetString(enum EnumType dummy); \
  enum EnumType Get##EnumType##Value(const char *string); \

/// define the access function names
#define DEFINE_ENUM(EnumType,ENUM_DEF) \
  const char *GetString(enum EnumType value) \
  { \
    switch(value) \
    { \
      ENUM_DEF(ENUM_CASE) \
      default: return ""; /* handle input error */ \
    } \
  } \
  enum EnumType Get##EnumType##Value(const char *str) \
  { \
    ENUM_DEF(ENUM_STRCMP) \
    return (enum EnumType)0; /* handle input error */ \
  } \
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
/******以下是测试代码**********************/
#define SOME_ENUM(XX) \
    XX(FirstValue,) \
    XX(SecondValue,) \
    XX(SomeOtherValue,=50) \
    XX(OneMoreValue,=100) \
    
    //通过上面的宏定义,来声明一个enum类型
    /*  等效代码:
    enum SomeEnum{
    FirstValue,
    SecondValue,
    SomeOtherValue=50,
    OneMoreValue=100} */
    DECLARE_ENUM(SomeEnum,SOME_ENUM)
    
    //通过上面的宏定义,来把实现 enum的值转化为字符串的函数 和 字符串转化为enum的值的函数
    DEFINE_ENUM(SomeEnum,SOME_ENUM)

int main(void)
  {
      char* retStr;
      int i;
      retStr = (char *)GetString(OneMoreValue);
      i = GetSomeEnumValue("SomeOtherValue");
      printf("The retStr is %s\n",retStr);
      printf("The GetVaule is %d\n",i);
      return 0;
  }

运行结果如图:

在这里插入图片描述

代码 (2/2)

main.c

#include <stdio.h>
#include <string.h>

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// The macros are defined in a more fundamental .h file (say defs.h);
#define ENUM_BEGIN(typ) enum typ {
#define ENUM(nam) nam
#define ENUM_END(typ) };

// 在这里是定义枚举变量
ENUM_BEGIN( Numbers )
    ENUM(ONE),
    ENUM(TWO),
    ENUM(THREE)
ENUM_END( Numbers )
// Now in one and only one .c file, redefine the ENUM macros and reinclude
//  the numbers.h file to build a string table
#undef ENUM_BEGIN
#undef ENUM
#undef ENUM_END
#define ENUM_BEGIN(typ) const char * typ ## _name_table [] = {
#define ENUM(nam) #nam
#define ENUM_END(typ) };

// 在这里是把枚举变量的名字都转化为字符串
ENUM_BEGIN( Numbers )
    ENUM(ONE),
    ENUM(TWO),
    ENUM(THREE)
ENUM_END( Numbers )
        
// Now you can do exactly what you want to do, with no retyping, and for any
//  number of enumerated types defined with the ENUM macro family
//  Your code follows;
char num_str[10];
int process_numbers_str(enum Numbers num) {
  switch(num) {
    case ONE:
    case TWO:
    case THREE:
    {
      strcpy(num_str, Numbers_name_table[num]); // eg TWO -> "TWO"
    } break;
    default:
      return 0; //no match
  }
  return 1;
}

// Sweet no ? After being frustrated by this for years, I finally came up
//  with this solution for my most recent project and plan to reuse the idea
//  forever
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
/******以下是测试代码**********************/


int main(void)
  {
      process_numbers_str(ONE);
      printf("The enum one is %s\n",num_str);
      process_numbers_str(TWO);
      printf("The enum two is %s\n",num_str);
      process_numbers_str(THREE);
      printf("The enum three is %s\n",num_str);
    return 0;
  }

运行结果如图:

在这里插入图片描述

三、参考网址

上两个代码主要部分都是直接复制于stackoverflow,链接如下:

https://stackoverflow.com/questions/147267/easy-way-to-use-variables-of-enum-types-as-string-in-c/202511#202511
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值