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 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include "clog.h"
union IntOrString {
int as_int;
char* as_string;
}; // SEMICOLON!!!!
// Declare an enum type 'WhichType' that can be either TYPE_INT or TYPE_STRING.
enum WhichType {
TYPE_INT, // == 0
TYPE_STRING // == 1
}; // SEMICOLON
// Internally, this will be stored as an int, but using an enum type makes it clear that variables
// of that type are flags that specify which (of a few choices) something is.
typedef struct {
union IntOrString value;
enum WhichType type;
} IntOrStringWithType;
void print_number_as_int_or_string(IntOrStringWithType number_as_int_or_string) {
if(number_as_int_or_string.type == TYPE_INT) {
printf("number_as_int_or_string is an int: %d\n", number_as_int_or_string.value.as_int);
}
else if(number_as_int_or_string.type == TYPE_STRING) {
printf("number_as_int_or_string is a string: %s\n", number_as_int_or_string.value.as_string);
}
}
int main(int argc, char* argv[]) {
IntOrStringWithType five = { .value.as_int = 5, .type = TYPE_INT };
print_number_as_int_or_string(five);
five.value.as_string = "cinco";
five.type = TYPE_STRING;
print_number_as_int_or_string(five);
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.