/* * demonstrate how a union works * * this sets up something as a float and then * accesses it as an integer * * Matt Bishop, ECS 36A, Fall 2019 */ #include #include /* * union to treat a variable * as either an integer or a float */ union floattoint { int x; /* ... as an integer */ float f; /* ... as a float */ }; /* * floating point number to use */ #define FLOAT 2.456 /* * and now the conversion */ int main(void) { union floattoint u; /* u can be treated as an integer or a float */ /* * give u a float value */ u.f = FLOAT; /* * now print it out as a float, a hexadecimal integer, * and a decimal integer */ printf("%f 0x%x %d\n", u.f, u.x, u.x); /* bye! */ return(0); }