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>
#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.
void print_number_as_int_or_string(union IntOrString number_as_int_or_string, enum WhichType type_of_number) {
if(type_of_number == TYPE_INT) {
printf("number_as_int_or_string is an int: %d\n", number_as_int_or_string.as_int);
}
else if(type_of_number == TYPE_STRING) {
printf("number_as_int_or_string is a string: %s\n", number_as_int_or_string.as_string);
}
}
int main(int argc, char* argv[]) {
union IntOrString five = { .as_int = 5 };
enum WhichType type_of_five = TYPE_INT;
print_number_as_int_or_string(five, type_of_five);
five.as_string = "cinco";
type_of_five = TYPE_STRING;
print_number_as_int_or_string(five, type_of_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.