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 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
union Number {
int as_int;
double as_double;
char as_char;
};
enum NumberType {
INT,
DOUBLE,
CHAR
}; // remember the semicolon
// Declare an enum type with three values: INT (=0), DOUBLE (=1), CHAR (=2).
// Stored internally as an int.
// Values are automatically numbered starting with 0.
// Value are guaranteed to be distinct.
// Values can be referred to directly, without every making an instance of the enum type.
void print_number(union Number n, int which) { // Better but still kinda bad! Use enum.
if(which == INT) {
printf("%d\n", n.as_int);
}
else if(which == DOUBLE) {
printf("%f\n", n.as_double);
}
else if(which == CHAR) {
printf("'%c'\n", n.as_char);
}
}
int main(int argc, char* argv[]) {
union Number n = { .as_double = 3.1415962 };
print_number(n, DOUBLE);
return EXIT_SUCCESS;
}
// double is like a float but twice the precision
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2024 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.