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\n",b.height);
    printf("%s\n",b.color);
    printf("%d\n",b.gears);
    printf("%f\n",b.q.weight);
    return 0;
}

转载于:https://www.cnblogs.com/c-x-a/p/11539751.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值