用c语言编程一个枚举,C语言中的共用体(union)和枚举(enum)
1 union
union Data{
int i;
char ch;
float f;
}a={1, 'a', 1.5}; //错误
union Data a = {16}; //正确
union Data a = {.ch = ‘j’}; //正确
在什么情况下使用共用体类型的数据?往往在数据处理中,有时需要对同一段空间安排不同的用途,这时用共用体类型比较方便,能增加程序处理的灵活性。
例如,学生的数据包括:姓名、号码、性别、职业、班级。
教师的数据包括:姓名、号码、性别、职业、职务。
要求用同一个表格来表示。
C语言核心代码
1 struct{2 int num; //成员 编号
3 char name[10]; //成员 姓名
4 char sex; //成员 性别
5 union{ //声明无名共用体类型
6 int class; //成员 班级
7 char position[10];//成员 职务
8 }category;9 }person[2];
View Code
2 enum
一个变量只有几种可能的值,则可以定义为枚举(enumeration)类型。
enumWeekday{sun=7, mon=1, tue, wed, thui, fri, sat} workday, weak_end; {}内,tue为2,wed为3,thu为4……。
enumWeekday{sun, mon, tue, wed, thui, fri, sat} workday, weak_end; {}内,sun=0, mon=1, tue为2,wed为3,thu为4……。
在枚举类型中,第一个枚举元素的值为0。
enum escapes//转移符
{
BELL = '\a',
BACKSPACE = '\b',
HTAB = '\t',
RETURN = '\r',
NEWLINE = '\n',
VTAB = '\v',
SPACE = ' '
};
1 #include
2
3
4
5 enum
6
7 {8
9 BELL = '\a',10
11 BACKSPACE = '\b',12
13 HTAB = '\t',14
15 RETURN = '\r',16
17 NEWLINE = '\n',18
19 VTAB = '\v',20
21 SPACE = ' '
22
23 };24
25
26
27 enum BOOLEAN { FALSE = 0, TRUE } match_flag;28
29
30
31 voidmain()32
33 {34
35 int index = 0;36
37 int count_of_letter = 0;38
39 int count_of_space = 0;40
41
42
43 char str[] = "I'm Ely efod";44
45
46
47 match_flag =FALSE;48
49
50
51 for(; str[index] != '\0'; index++)52
53 if( SPACE !=str[index] )54
55 count_of_letter++;56
57 else
58
59 {60
61 match_flag = (enum BOOLEAN) 1;62
63 count_of_space++;64
65 }66
67
68 printf("%s %d times %c", match_flag ? "match" : "not match", count_of_space, NEWLINE);69
70 printf("count of letters: %d %c%c", count_of_letter, NEWLINE, RETURN);71
72 }
View Code