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
#include <stdio.h>
#include <stdlib.h>
//#include "clog.h"

typedef union {
    int   as_int;
    float as_float;
} Number;
// Just like a struct type, except only *one* of the fields will be stored.

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

    Number n1 = { .as_int   = 5   };
    Number n2 = { .as_float = 0.2 };

    /* // RIGHT */
    /* log_int(n1.as_int); */
    /* log_float(n2.as_float); */

    // WRONG:  Pretend we forgot which type of data is stored.
    /* log_float(n1.as_float);  // WRONG */
    /* log_int(n2.as_int);      // WRONG */

    // LESSONS:
    // 1. Compiler does not keep track of which field (type) is stored
    // 2. You have to keep track.
    
    return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

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