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:
“There is a difference between a book of two hundred pages from the very beginning, and a book of two hundred pages which is the result of an original eight hundred pages. The six hundred are there. Only you dont see them.”
—Elie Wiesel (b. 1928)
“Lady Hodmarsh and the duchess immediately assumed the clinging affability that persons of rank assume with their inferiors in order to show them that they are not in the least conscious of any difference in station between them.”
—W. Somerset Maugham (18741965)
“In externals we advance with lightening express speed, in modes of thought and sympathy we lumber on in stage-coach fashion.”
—Frances E. Willard 18391898, U.S. president of the Womens Christian Temperance Union 1879-1891, author, activist. The Womans Magazine, pp. 137-40 (January 1887)
“A committee is organic rather than mechanical in its nature: it is not a structure but a plant. It takes root and grows, it flowers, wilts, and dies, scattering the seed from which other committees will bloom in their turn.”
—C. Northcote Parkinson (19091993)