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 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
// UNION
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;
int main(int argc, char* argv[]) {
union Value n = { .as_int = 5 };
// Declare 'union Value' object and set the .as_int field.
printf("n.as_int == %d\n", n.as_int);
n.as_float = 3.1415;
printf("n.as_float == %.4f\n", n.as_float);
printf("n.as_int == %d // WRONG!!!\n", n.as_int);
union Value n_do_not_do_this = { .as_int = 7, .as_float = 4.2526 };
printf("n_do_not_do_this.as_int == %d\n", n_do_not_do_this.as_int);
printf("n_do_not_do_this.as_float == %.4f\n", n_do_not_do_this.as_float);
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.