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
//#define INT 1
//#define FLOAT 2
enum ValueType { // name just like a struct or union type, capital camel case
INT,
FLOAT
};
// Use enum type for a variable that represents a choice or category.
// Internally, it will be stored just like an int (4 bytes on our platform).
// Fields will be automatically numbered (and distinct).
// Field list is comma separated (different from struct or union).
// Name fields with all caps, underscore case (INT_TYPE not intType or IntType or int_type)
union Value {
int as_int; // 4 bytes (on our platform)
float as_float; // 4 bytes (on our platform)
}; // 4 bytes (on our platform) for a 'union Value' object
// could have done typedef union { ... } Value;
//void print_value(union Value n, int which) { // WRONG: Do not use int constant as flag
void print_value(union Value n, enum ValueType which) { // GOOD
if(which == INT) {
printf("n.as_int == %d\n", n.as_int);
}
if(which == FLOAT) {
printf("n.as_float == %.4f\n", n.as_float);
}
}
int main(int argc, char* argv[]) {
union Value n = { .as_int = 5 };
print_value(n, INT);
return EXIT_SUCCESS;
}
/* 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.