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


// Declare an enum type 'WhichType' that can be either TYPE_INT or TYPE_STRING.
// Internally, this will be stored as an int, but using an enum type makes it clear that variables
// of that type are flags that specify which (of a few choices) something is.

typedef struct {
    enum {  // This enum type cannot be used anywhere else because we didn't give it a name.
        TYPE_INT,    // == 0
        TYPE_STRING  // == 1
    } type;  // , but we have a field called .type
    union {
        int as_int;
        char* as_string;
    };  // ANONYMOUS
} IntOrStringWithType;

void print_number_as_int_or_string(IntOrStringWithType number_as_int_or_string) {
    if(number_as_int_or_string.type == TYPE_INT) {
        printf("number_as_int_or_string is an int: %d\n", number_as_int_or_string.as_int);
    }
    else if(number_as_int_or_string.type == TYPE_STRING) {
        printf("number_as_int_or_string is a string: %s\n", number_as_int_or_string.as_string);
    }
}

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

    IntOrStringWithType five = { .as_int = 5,
                                 .type = TYPE_INT };
    print_number_as_int_or_string(five);

    five.as_string = "cinco";
    five.type = TYPE_STRING;
    print_number_as_int_or_string(five);

    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.