本质是一个变量,这个变量在不同时刻可以存放指定的不同类型的数据。
- 如果你有这样的需求,一个变量这段时间想是int类型,过段时间想是double类型…这时可以考虑使用联合体
联合体声明
union 联合体名{
数据类型1 变量名;
数据类型2 变量名;
...
数据类型n 变量名;
};
- 这种联合体类型可以存放多种数据类型的数值,但是同一时间只能存放一种数据类型的变量
联合体元素访问 - 使用上和结构体访问是一样的
- 但是联合体同一时间只有一个成员是有效的
- 必须要做好联合体存储类型的跟踪,保证访问的元素是有效的
代码示例
#include <stdio.h>
int main(int argc, char const *argv[])
{
enum u_type{U_INT, U_DOUBLE, U_STRING}; //追踪当前联合体中存储的类型
union u_sample{
int a;
double f;
char *string;
} u1; //联合体类型变量u1
union u_sample *pu = &u1; //也可有指向联合体的指针
int u_now_type = U_INT;
u1.a = 10;
printf("union now is %d\n", u1.a);
printf("union double is not sure: %f\n", u1.f); //这样的结果是不确定的
u_now_type = U_DOUBLE;
pu -> f = 10.1;
printf("union now is %f\n", u1.f);
u_now_type = U_STRING;
u1.string = "hello";
printf("union now is %s\n", u1.string);
return 0;
}
运行结果:
union now is 10
union double is not sure: 0.000000
union now is 10.100000
union now is hello