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

// Define a union type called “union IntOrString” that can contain EITHER an int OR a char* --- BUT NOT BOTH.
union IntOrString {
    int as_int;
    char* as_string;
};  // REMEMBER THE SEMICOLON

// Objects of type 'union IntOrString' can contain EITHER an int (accessed as .as_int) or a char* (accessed as .as_string)
// but NOT BOTH.

// You have to keep track of which type an object currently contains.

// Object occupies only as as much memory (# of bytes) as the largest field in it.
// .as_int occupies 4 bytes on our platform
// .as_string occupies 8 bytes on our platform
// A union IntOrString object occupies 8 bytes on our platform.

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

    // Declare a variable of type “union IntOrString” called “o”.
    union IntOrString o;
    o.as_int = 5;
    printf("o.as_int == %d\n", o.as_int);

    o.as_string = "FIVE";  // this overwrites the memory where .as_int was stored.  The 5 is gone!!!
    printf("o.as_string == %s\n", o.as_string);

    printf("o.as_int == %d  (PROBLEM)\n", o.as_int);   // PROBLEM:  .as_int has been ovewrritten

    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.