#include <stdio.h> #include <stdlib.h> union IFC { int i; float f; char c; }; int main(void) { union IFC ifc = {.f = 3.14}; printf("Union's float is %.2f\n", ifc.f); // 3.14 ifc.i = 2; printf("Union's integer is %d\n", ifc.i); // 2 ifc.c = 'A'; printf("Union's character is %c\n", ifc.c); // A printf("Union's float is %.2f\n", ifc.f); // 0.00 return 0; } How does this code work at the memory level of the computer? Where inf.f value 0.00 from inf.f from when the union uses inf.c ? I understand that one union occupies the same number of bytes in any state allowed for it (in my case, int / float / char ). But after all, these bytes store only one value. Why, if at the given moment of time the 'A' symbol is stored there, can I still contact the union for the real number inf.f ? Although it is not what I once asked, although it always equals zero, it still returns. How it works?
unions are used as a 'fast' converter of one to another, because the memory for all 'convertible' elements is the same. - NewView