1)
union mytypes_t {
char c;
int i;
float f;
} mytypes;
Each of these members is of a different data type. But since all of them are referring to the same location in memory, the modification of one of the members will affect the value of all of them. It is not possible to store different values in them in a way that each is independent of the others.
How come same location and mytypes.c ,mytypes.i ,mytypes.f can hold different values?
2)
What is the difference between unions and data structures?and what is the purpose in unions to have each member size equal to the largest union member size?
3)
also in this example:
struct {
char title[50];
char author[50];
union {
float dollars;
int yen;
};
} book;
It is written "because it is a union (not a structure), the members dollars and yen actually share the same memory location, so they cannot be used to store two different values simultaneously. The price can be set in dollars or in yen, but not in both simultaneously".However , If you write a program and give book.dollars a value and book.yen another value .you can use cout to get the two different values you entered
1) They have different types so the memory will be interpreted differently which means the values will be different.
2) Have a guess.
3) You can only use one union member at a time. I think the struct should have a variable to keep track of if the money is dollar or yen so that you know what to use. If you give dollars a value and then print yen, the behaviour is undefined, meaning anything could happen. In your little test the compiler probably assumed the value that was last written to dollar and yen were the values they contained and printed them directly without actually reading them from the struct.