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 | #include <stdio.h>
#include <stdlib.h>
#include <assert.h>
/* const int NUMBER_FLOAT = 1; */
/* const int NUMBER_INT = 2; */
typedef enum { NUMBER_INT = 1, NUMBER_FLOAT } NumberType;
// The ` = 1` protects you against messing up and writing if(number_type) {}
typedef union {
int as_int;
float as_float;
} Number;
void print_number(Number n, NumberType number_type) {
if(number_type == NUMBER_INT) {
printf("n: %d\n", n.as_int);
}
else {
assert(number_type == NUMBER_FLOAT); // HIGHLY RECOMMENDED!!!!
printf("n: %.060f\n", n.as_float);
}
// else if(number_type == NUMBER_FLOAT) {
// printf("n: %.060f\n", n.as_float);
// }
// else {
// assert(false); // UNKNOWN NUMBER TYPE
// }
}
int main(int argc, char* argv[]) {
Number n1 = { .as_float = 0.25 };
Number n2 = { .as_int = 1024 };
print_number(n1, NUMBER_FLOAT);
print_number(n2, NUMBER_INT);
return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2019 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.