summaryrefslogtreecommitdiff
path: root/C/HF/chap5/data.c
diff options
context:
space:
mode:
Diffstat (limited to 'C/HF/chap5/data.c')
-rw-r--r--C/HF/chap5/data.c46
1 files changed, 46 insertions, 0 deletions
diff --git a/C/HF/chap5/data.c b/C/HF/chap5/data.c
new file mode 100644
index 0000000..4034480
--- /dev/null
+++ b/C/HF/chap5/data.c
@@ -0,0 +1,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;
+}