`
aqingsao
  • 浏览: 173349 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

enum in c

阅读更多

在c中定义一个enum类型很容易:

enum _pet_type{DOG, CAT, COW};

但是使用为了方便,可以使用typedef来定义:

typedef enum _pet_type{DOG, CAT, COW} pet_type;

这样就可以直接这样使用了:pet_type type = DOG;

1. 关于枚举数值

在这样的定义中,DOG被赋予了整型值0,后面的依次加1。你可以指定某一项元素的整数值,其后的元素依然是依次加1。

比如 typedef enum _pet_type{DOG, CAT = 10, COW} pet_type;

则DOG的值是0, CAT是10, COW是11。

2. 枚举数值与字符串的互换?

关于enum经常遇到的一个问题是,需要在字符串和整数值之间进行转换。比如遇到了枚举类型DOG,想显示字符串“DOG”,而不是数字? 拿到一个字符串“DOG”,怎样才能转换成枚举类型DOG,或者整数0?

了解了enum的原理,会发现直接转换不太可能. 因为c中enum类似与宏,比如定义了#define DOG 0,这样编译预处理时已经把所有的DOG替换成了0。enum与之类似, 每个枚举的符号(DOG、CAT、COW)都会被替换成数字,这样在运行期,只存在数字0、1、2,而完全没有了任何枚举符号DOG、CAT等的信息。所以想做一些简单直接的转换是不可能的,只能自己来写。

 

比如,从枚举类型得到对应的字符串,手工写一个转换函数:

static char *enum_to_name(pet_type type){
	switch(type){
		case DOG:
		return "DOG";
		case CAT:
		return "CAT";
		case COW:
		return "COW";
		default:
		return NULL;
	}
}

int main (int argc, char const *argv[])
{
	char *name = enum_to_name(DOG);
	printf("DOG name is \"%s\"\n", name);
	return 0;
} 

 

同样的,可以写从字符串到枚举数字的转换函数。当然,如果枚举类型比较多,而且所有枚举值是连续的话,可以写的简单一点:

typedef enum _pet_type{DOG, CAT, COW}pet_type;

static pet_type get_pet_type(char *data){
	char map[][4] = {"DOG", "CAT", "COW"};
	int i;
	for (i = 0; i < 3; ++i)
        {
        if (strcmp (map[i], data) == 0)
        {
		return i;
        }
    }
	return -1;
}

int main (int argc, char const *argv[])
{
	pet_type type = get_pet_type("DOG");
	printf("\"DOG\" type is %d\n", type);
	return 0;
} 

 3. 在enum中定义ENUM_COUNT

有时候会使用枚举类型的数量,可能与硬编码。此时,可以在enum时定义一个元素ENUM_COUNT。由于默认情况下对应的整数值自动加1,所以这个值恰好代表了enum类型的数量:

typedef enum _pet_type{DOG, CAT, COW, PET_COUNT}pet_type;
这样如果对枚举类型进行增删,所有的PET_COUNT的引用不需要进行修改。

 

分享到:
评论

相关推荐

    enum-props:枚举,支持其他元数据

    // define a simple enum (automatically flaggable -&gt; A: 0x01, B: 0x02, C: 0x04) //Uses bitwise 'OR' operation in between the values and creates enumerated constants. For example, if 'Read':1, 'Write':2...

    C.Programming.Step.By.Step.Beginners.To.Experts.Edition.B011EXMV7Q

    Did you know many expert developers have started with learning C in order to become knowledgeable in computer programming? Were you aware that your children are learning C Programming today in their ...

    编译原理PL0源码(C语言版)

    编译原理PL0源码(C语言版) /*** PL0 COMPILER WITH CODE GENERATION ***/ //--------------------------------------------------------------------------- #include #pragma hdrstop #include "Unit1.h" //----...

    C.in.Depth.Easy.Beginners.To.Experts.Guide.1500481033

    Learn the all basics and advanced features of C programming in no time from Bestselling Programming Author Harry. H. Chaudhary. This Book, starts with the basics; I promise this book will make you ...

    C.Quick.Syntax.Reference

    C's efficiency makes it a popular choice in a wide variety of applications and operating systems with special applicability to, for instance, wearables, game programming, system level programming, ...

    C.Programming.Professional.For.Beginners.B011A2PX30

    Did you know many expert developers have started with learning C in order to become knowledgeable in computer programming? Were you aware that grade schools and high schools have begun implementing C...

    C.Programming.The.Ultimate.Way.to.Learn.C.1500481114

    Learn the all basics and advanced features of C programming in no time from Bestselling Programming Author Harry. H. Chaudhary. This Book, starts with the basics; I promise this book will make you ...

    c++ 尽量不要使用#define 而是用const、enum、inline替换。

    例如:这里程序文件开头有如下#define语句 代码如下: #define N 10 #define PI 3.14 #define MAX 10000 #define Heigth 6.65 … … 假设这里程序运行出错误,而且就是在我们使用这些常量有错误,此时编辑器应该会抛...

    AD7689通用驱动C语言代码

    #define AD7689_CFG_INX_MSK NO_OS_GENMASK(9,7) #define AD7689_CFG_BW_MSK NO_OS_BIT(6) #define AD7689_CFG_REF_MSK NO_OS_GENMASK(5,3) #define AD7689_CFG_SEQ_MSK NO_OS_GENMASK(2,1) #define AD7689_CFG_RB_...

    C.Programming.The.Definitive.Beginners.Reference.1500481009

    Learn the all basics and advanced features of C programming in no time from Bestselling Programming Author Harry. H. Chaudhary. This Book, starts with the basics; I promise this book will make you ...

    Thinking in C++高清版

    7.4.1 类里的const和enum 133 7.4.2 编译期间类里的常量 134 7.4.3 const对象和成员函数 136 7.4.4 只读存储能力 139 7.5 可变的(volatile) 140 7.6 小结 141 7.7 练习 141 第8章 内联函数 142 8.1 预处理器的缺陷...

    《你必须知道的495个C语言问题》

    3.20 “semantics of‘’change in ANSI C”的警告是什么意思? 42 3.21 “无符号保护”和“值保护”规则的区别在哪里? 42 第4章 指针 45 基本的指针应用 45 4.1 指针到底有什么好处? 45 4.2 我想声明...

    C++大学教程,一本适合初学者的入门教材(part2)

    20.5.9 inplace_merge、 unique—copy和reverse—copy 20.5.10 集合操作 20.5.11 1ower—bound、 upper—bound和equal_range 20.5.12 堆排序 20.5.13 min和max 20.5.14 本章未介绍的算法 20.6 bitset类...

    虚拟串口设备驱动源码 ver 04.1.15

    只是改动了toaster\inc\public.h中的#define BUS_HARDWARE_IDS L"Toaster\\MsToaster\0" 3. 控制台上运行enum -p 2,添加第二个虚拟串口设备 4. 控制台上运行test.exe,枚举并且互连刚刚生成的两个串口。 5. 打开...

    C语言安全编码之数组索引位的合法范围

    C语言中的数组索引必须保证位于合法的范围内! 示例代码如下: enum {TABLESIZE = 100}; int *table = NULL; int insert_in_table(int pos, int value) { if(!table) { table = (int *)malloc(sizeof(int) *TABLE...

    determine_c_or_cpp:从C ++以及各种版本中以编程方式确定C

    // returns 8 in C and 100 in C++ } 我在使用了此示例 C使用struct,union和enum标签作为名称空间的原始形式, 。 因此,以下代码将为C提供sizeof int,为C ++提供sizeof struct T # include extern int T; int...

    GObject Reference Manual

    glib-mkenums - C language enum description generation utility glib-genmarshal - C code marshaller generation utility for GLib closures gobject-query - display a tree of types IV. Tutorial How To ...

    Turbo C++ 3.0[DISK]

    command-line compiler assume a .c extension and C language source, use the command-line option -P-c. For more information, see "The command-line compiler" in the User's Guide. - Note that the ...

    Turbo C++ 3.00[DISK]

    command-line compiler assume a .c extension and C language source, use the command-line option -P-c. For more information, see "The command-line compiler" in the User's Guide. - Note that the ...

    uCOS-II v2.52 在 STM32 上的移植

    ..\..\Libraries\STM32F10x_StdPeriph_Driver\inc; ..\..\App; ..\..\Driver; ..\..\OS; ..\..\OS\port (6) Linker, Use memory layout from target dialog. (7) ...

Global site tag (gtag.js) - Google Analytics