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>

typedef struct {
    enum  { ELEMENT_INT, ELEMENT_STRING } type;
    union {
        int    as_int;
        char*  as_string;
    }; // ANONYMOUS union (C11).
} Element;

void print_element_simple(Element element) {
    if(element.type == ELEMENT_INT) {
        printf("element.as_int == %d\n", element.as_int);
    }
    else if(element.type == ELEMENT_STRING) {
        printf("element.as_string == \"%s\"\n", element.as_string);
    }
}

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

    Element element1 = { .type = ELEMENT_INT,
                         .as_int = 5 };  // do not attempt to initialize .as_int and .as_string in the same object
    print_element_simple(element1);

    Element element2 = { .type = ELEMENT_STRING,
                         .as_string = "Pithus" };
    print_element_simple(element2);
    
    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.