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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>

// UNION -- using typedef syntax
// ENUM --- using typedef syntax

typedef union {
    int   as_int;   // 4 bytes¹
    float as_float; // 4 bytes¹
    char* as_string;// 8 bytes¹
} Number; // 8 bytes¹  (max size of the fields)
// ¹ on our platform

typedef enum {
    TYPE_UNINITIALIZED,
    TYPE_INT,
    TYPE_FLOAT,
    TYPE_STRING
} NumberType;

//enum NumberType {
//  TYPE_UNINITIALIZED,
//  TYPE_INT,
//  TYPE_FLOAT,
//  TYPE_STRING
//};

void print_number(Number n, NumberType type) {
//void print_number(Number n, enum NumberType type) {
    if(type == TYPE_INT) {
        printf("n has the value %d\n", n.as_int);
    }
    else if(type == TYPE_FLOAT) {
        printf("n has the value %.08f\n", n.as_float);
    }
    else if(type == TYPE_STRING) {
        printf("n has the value %s\n", n.as_string);
    }
}

int main(int argc, char* argv[]) {

    Number  n = { .as_int = 3 };   // named initializer
    print_number(n, TYPE_INT);

    n.as_float = 3.1415; // This overwrites the bytes in which the int value was stored.
    print_number(n, TYPE_FLOAT);
    
    n.as_string = "e"; // This overwrites the bytes in which the float value was stored.
    print_number(n, TYPE_STRING);

    printf("TYPE_INT    == %d\n", TYPE_INT);
    printf("TYPE_FLOAT  == %d\n", TYPE_FLOAT);
    printf("TYPE_STRING == %d\n", TYPE_STRING);

    return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

© Copyright 2022 Alexander J. Quinn         This content is protected and may not be shared, uploaded, or distributed.