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 45 46 47 48 49 50 51 52 53 54 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
// ANONYMOUS UNION TYPE inside a struct type
//
// FINAL PRODUCT without the comments
typedef struct { // 'Number' will now include both the value and the type.
union {
int as_int;
float as_float;
char* as_string;
};
enum NumberType {
TYPE_UNINITIALIZED,
TYPE_INT,
TYPE_FLOAT,
TYPE_STRING
} type;
} Number;
void print_number(Number n) {
if(n.type == TYPE_INT) {
printf("n has the value %d\n", n.as_int);
}
else if(n.type == TYPE_FLOAT) {
printf("n has the value %.08f\n", n.as_float);
}
else if(n.type == TYPE_STRING) {
printf("n has the value %s\n", n.as_string);
}
}
int main(int argc, char* argv[]) {
Number n = { .as_int = 3, .type = TYPE_INT };
print_number(n);
n = (Number) { .as_float = 3.1415, .type = TYPE_FLOAT };
print_number(n);
n = (Number) { .as_string = "e", .type = TYPE_STRING };
print_number(n);
printf("TYPE_INT == %d\n", TYPE_INT);
printf("TYPE_FLOAT == %d\n", TYPE_FLOAT);
printf("TYPE_STRING == %d\n", TYPE_STRING);
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.