标签:
1.联合:计算机为其中最大的字段分配空间。
例如:
typedef union
{
short count;
float weight;
float volume;
}quantity; //占4字节
2.设置联合的值
C89方式(保存第一个字段的值):quantity q = {4}; 注意加上{}
指定初始化器(按名设置联合字段的值):quantity q = {.weight=1.5}; 也能设置结构字段的初值
点表示法: quantity q;
q.volume = 3.7;
3.结构体常和联合体一起使用
例如:
typedef union { float lemon; int lime_pieces; }lemon_lime; typedef struct { float tequila; float cointreau; lemon_lime citrus; }margarita; margarita m = {2.0,1.0,{0.5}}; margarita b = {2.0,1.0,{.line_pieces=1}};
4.枚举
enum colors {red,green,puce};
enum colors favorite = puce;
5.结构和联合用分号分割数据项,而枚举用逗号
练习(枚举)
#include <stdio.h> typedef enum { COUNT,POUNDS,PINTS }unit_of_measure; typedef union { short count; float weight; float volume; }quantity; typedef struct { const char *name; const char *country; quantity amount; unit_of_measure units; }fruit_order; void display(fruit_order order) { printf("This order contains"); if(order.units == PINTS) printf("%2.2f pints of %s\n",order.amount.volume,order.name); else if (order.units == POUNDS) printf("%2.2f lbs of %s\n",order.amount.weight,order.name); else printf("%i %s\n",order.amount.count,order.name); } int main() { fruit_order apples = {"apples","England",.amount.count=144,COUNT}; fruit_order strawberries = {"strawberries","Spain",.amount.weight=17.6,POUNDS}; fruit_order oj = {"orange juice","U.S.A",.amount.volume=10.5,PINTS}; display(apples); display(strawberries); display(oj); return 0; }
标签:
原文地址:http://www.cnblogs.com/syyy/p/5700917.html