Union (computer Science) - Difference Between Union and Structure

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:

    It is so wonderful to our neurologists that a man can see without his eyes, that it does not occur to them that is just as wonderful that he should see with them; and that is ever the difference between the wise and the unwise: the latter wonders at what is unusual, the wise man wonders at the usual.
    Ralph Waldo Emerson (1803–1882)

    Life is a disease; and the only difference between one man and another is the stage of the disease at which he lives. You are always at the crisis: I am always in the convalescent stage.
    George Bernard Shaw (1856–1950)

    One thing that makes art different from life is that in art things have a shape ... it allows us to fix our emotions on events at the moment they occur, it permits a union of heart and mind and tongue and tear.
    Marilyn French (b. 1929)

    The question is still asked of women: “How do you propose to answer the need for child care?” That is an obvious attempt to structure conflict in the old terms. The questions are rather: “If we as a human community want children, how does the total society propose to provide for them?”
    Jean Baker Miller (20th century)