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 55 56 57 58 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
typedef union {
int as_int;
float as_float;
char* as_string;
} NumberValue;
typedef enum { // This is similar to if we had done this:
TYPE_UNINITIALIZED, // #define TYPE_UNINITIALIZED 0
TYPE_INT, // #define TYPE_INT 1
TYPE_FLOAT, // …
TYPE_STRING // …
} NumberType; // typedef int NumberType
// But always use the enum type, if appropriate.
// Compiler automatically assigns a value (an int) to each of the enum constants.
typedef struct { // 'Number' will now include both the value and the type.
NumberValue value;
NumberType type;
} Number;
void print_number(Number n) {
if(n.type == TYPE_INT) {
printf("n has the value %d\n", n.value.as_int);
}
else if(n.type == TYPE_FLOAT) {
printf("n has the value %.08f\n", n.value.as_float);
}
else if(n.type == TYPE_STRING) {
printf("n has the value %s\n", n.value.as_string);
}
}
int main(int argc, char* argv[]) {
Number n = { .value = { .as_int = 3 }, .type = TYPE_INT };
print_number(n);
n.value.as_float = 3.1415;
n.type = TYPE_FLOAT;
print_number(n);
n.value.as_string = "e";
n.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.