Difference Between Union and Structure
A union is a class all of whose data members are mapped to the same address within its object. The size of an object of a union is, therefore, the size of its largest data member.
In a structure, all of its data members are stored in contiguous memory locations. The size of an object of a struct is, therefore, the size of the sum of all its data members.
This gain in space efficiency, while valuable in certain circumstances, comes at a great cost of safety: the program logic must ensure that it only reads the field most recently written along all possible execution paths. The exception is when unions are used for type conversion: in this case, a certain field is written and the subsequently read field is deliberately different.
An example illustrating this point is:
+-----+-----+ struct { int a; float b } gives | a | b | +-----+-----+ ^ ^ | | memory location: 150 154 | V +-----+ union { int a; float b } gives | a | | b | +-----+Structures are used where an "object" is composed of other objects, like a point object consisting of two integers, those being the x and y coordinates:
typedef struct { int x; // x and y are separate int y; } tPoint;Unions are typically used in situation where an object can be one of many things but only one at a time, such as a type-less storage system:
typedef enum { STR, INT } tType; typedef struct { tType typ; // typ is separate. union { int ival; // ival and sval occupy same memory. char *sval; } } tVal;Read more about this topic: Union (computer Science)
Famous quotes containing the words difference between, difference, union and/or structure:
“The first idea that the child must acquire, in order to be actively disciplined, is that of the difference between good and evil; and the task of the educator lies in seeing that the child does not confound good with immobility and evil with activity.”
—Maria Montessori (18701952)
“The difference between a moral man and a man of honor is that the latter regrets a discreditable act, even when it has worked and he has not been caught.”
—H.L. (Henry Lewis)
“My whole working philosophy is that the only stable happiness for mankind is that it shall live married in blessed union to woman-kindintimacy, physical and psychical between a man and his wife. I wish to add that my state of bliss is by no means perfect.”
—D.H. (David Herbert)
“... the structure of our public morality crashed to earth. Above its grave a tombstone read, Be toleranteven of evil. Logically the next step would be to say to our commonwealths criminals, I disagree that its all right to rob and murder, but naturally I respect your opinion. Tolerance is only complacence when it makes no distinction between right and wrong.”
—Sarah Patton Boyle, U.S. civil rights activist and author. The Desegregated Heart, part 2, ch. 2 (1962)