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

// Define union type 'Number'
union Number {
    int as_int;
    double as_double;
};  // <<<< SEMICOLON <<<<

int main(int argc, char* argv[]) {
    union Number n = { .as_double = 9839283839293.23982473249 };
    printf("n.as_double == %f\n", n.as_double);  // 👌
    
    // Q: What about .as_int?
    // A: Union object can hold only one of its fields.  They share the same space.
    log_int(n.as_int);

    // Union object
    // ∙ Field share the same memory.
    // ∙ Only one field can be used to store a value.
    // ∙ Compiler does not check if you try to misuse it.
    // ∙ Syntax looks the same as a struct, except you can only initialize one field.
    //
    // IT'S ALL JUST BYTES.

    // union Number problem = { .as_int = 5, .as_double = 0.25 };  // <<<< WRONG!!! <<<< 
    // printf("problem.as_double == %f\n", problem.as_double);
    // log_int(problem.as_int);

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

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