1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
#include <stdio.h>
enum q {
COUNT,
WEIGHT,
VOLUME,
};
/* Using anonymous data structures is awesome */
struct item {
char *desc;
union {
long int count;
float weight;
float volume;
};
enum q type;
}__attribute((packed))__;
int main(void) {
struct item fruit =
{
.desc = "apple",
};
fruit.type = WEIGHT;
if (fruit.type == COUNT) {
fruit.weight = 3.87;
printf("Fruit = %s is %ld\n", fruit.desc, fruit.count);
}
if (fruit.type == WEIGHT) {
fruit.weight = 69.5;
printf("Fruit = %s is %2.2f\n", fruit.desc, fruit.weight);
}
if (fruit.type == VOLUME) {
fruit.volume = 63.5;
printf("Fruit = %s is %2.2f\n", fruit.desc, fruit.volume);
}
printf("struct item: %lu - count: %lu - weight: %lu - volume: %lu - type: %lu\n",
sizeof(struct item), sizeof(fruit.count), sizeof(fruit.weight),
sizeof(fruit.volume), sizeof(fruit.type));
return 0;
}
|