// *** 以前 ***
//C99:结构体内的联合体需要一个成员名,
//每次访问都要经过它
struct ShapeOld {
int kind;
union {
double radius;
struct {
double width;
double height;
} rect;
} u;
};
struct ShapeOld boxOld;
boxOld.kind = 1;
boxOld.u.rect.width = 3;
boxOld.u.rect.height = 4;
double areaOld = boxOld.u.rect.width * boxOld.u.rect.height;
//areaOld is 12
printf("areaOld is %g\n", areaOld);
// *** 在 C11 版本中 ***
//没有名字的成员:它的字段属于外层结构体
struct Shape {
int kind;
union {
double radius;
struct {
double width;
double height;
};
};
};
struct Shape box = {.kind = 1, .width = 3, .height = 4};
double area = box.width * box.height;
//area is 12
printf("area is %g\n", area);