@Chita_
C语言 用户定义类型
- 枚举(Enumeration)
- 共用体(Union)
背景
基本数据类型
- int: 整型
- char: 字符型
- float:浮点型
- double: 双精度浮点型
派生数据类型
- Arrays
- Strings
- Structures
- Unions
用户定义的数据类型
- 枚举类型
使用枚举的动机
- 通常,一个变量只能取几个可能的离散值
- 宏通常用于定义符号常量,表示变量的可能值
- 枚举是一种更好的选择
#define COLOR_RED 0
#define COLOR_YELLOW 1
#define COLOR_GREEN 2
int main(void)
{
int color;
// can either be 0, 1 or 2
…
color = COLOR_GREEN;
}
枚举
枚举是用户定义的数据类型,用于将标识符分配给整数常量
enum enum_tag {name_0, name_1, ..., name_n} variable_list;
- 定义一个新的枚举类型
- 定义从0到n的整数值的符号常量
->name_0 的值为 0, name_1的值为 1, 等等 - enum_tag 和 variable_list是可选的
举例说明
enum colors { red, yellow, green };
- 定义一个新的枚举类型枚举颜色
- 定义三个整数常量:为红色赋值0,为黄色赋值1,为绿色赋值2
- 任何枚举颜色类型或基本数据类型的变量都可以被指定为红色、黄色或绿色
- 可以重写整数赋值,例如:
enum colors {red = 3, yellow = 2, green = 1};
- Typedef可用于为新类型创建别名,例如:
typedef enum colors {red = 3, yellow = 2, green = 1} color_t;
- Color_ t是一种新的类型,可以用来声明变量
如果一个标识符被分配了一个值,而后续的标识符没有被分配,则后续的标识符将从分配的值继续前进。
enum colors { red, yellow = 3, green, blue };
红色被赋值为0,黄色被赋值为3,绿色被赋值为4,蓝色被赋值为5。
举例(1)
#include <stdio.h>
/* Declaration defines new enumerated type and integer constants */
enum colors { red, yellow = 3, green, blue };
int main(void)
{
/* Declaration defines variables of type enum colors */
/* Can take values of red, yellow, green or blue */
enum colors fgcolor = blue, bgcolor = yellow;
printf ("%d %d\n", fgcolor, bgcolor);
/* Will print 5 3 */
return 0;
}
举例(2)
#include <stdio.h>
/* Declaration defines integer constants */
enum { red, yellow = 3, green, blue };
int main(void)
{
/* Declaration defines variables of type int */
/* Can be assigned red, yellow, green or blue */
int fgcolor = blue, bgcolor = yellow;
printf ("%d %d\n", fgcolor, bgcolor);
/* Will print 5 3 */
return 0;
}
重复的标识符
不能重用枚举类型中的标识符来声明同一作用域中的新变量或枚举
void func(void)
{
enum colors { red, yellow, black };
enum rgb { red, green, blue };
…
}
void func(void)
{
enum colors { red, yellow, black };
int red;
…
}
由于在同一范围内重用标识符红色,将不会编译。
共用体
共用体类似于结构体,但不同的字段在内存中占用相同的空间
union union_tag {
type1 member1;
type2 member2;
...
} variable_list;
- union_tag 是共用体的名字
- union_tag 和 variable_list 是可选择的
- 如果未指定union_tag,则应指定variable_list;否则,就无法使用未命名的联合类型声明变量
共用体成员可以是
- 基本数据类型
- 派生类型和用户定义类型
- 指向基本、派生和用户定义数据类型的指针
- 函数指针
共用体 vs 结构体
结构体 | 共用体 | |
---|---|---|
存储分配 | 为所有成员分别分配存储空间 | 1.为其所有成员分配公共存储空间 2. 分配空间来容纳最大的成员 |
访问 | 所有成员可以同时访问 | 在任何给定时间,只有一个成员是“活动的” |
联合vs结构:存储分配
struct space {
int i;
float f;
char c[4];
};
union space {
int i;
float f;
char c[4];
};
sizeof(struct space) = sizeof(i) + sizeof(f) + sizeof( c )
sizeof(union space) = max(sizeof(i), sizeof(f), sizeof( c ))