C语言联合

联合使用关键字union,表示的一种量,只占用一块内存,具体如何占用取决于类型最大的那个。比如int和float会选用float。
联合也可以和结构体结合起来用,也可以赋值,通过.属性名的方式指定初始化器,对指定对象赋值,其他的不变。

#include<stdio.h>
typedef union{
    short count;
    float weight;
    float volume;

} quantity;
typedef struct{
    const char* color;
    int gears;
    int height;
    quantity q;
} bike;

int main(){
    //通过.属性名的方式指定初始化器,对指定对象赋值,其他的不变
    bike b= {.height=3,.color="red",.q.weight=12}; 
    //.q表示给结构体的quantity赋值,后面接着.weight是给联合quantity里的weight进行赋值。
    printf("%d
",b.height);
    printf("%s
",b.color);
    printf("%d
",b.gears);
    printf("%f
",b.q.weight);
    return 0;
}
原文地址:https://www.cnblogs.com/c-x-a/p/11539751.html