Differences between structure and union in C programming with example

By | August 5, 2015

What are the differences between structure and union? Give one illustrative example of usage of the union. 8m Jun2008

Structure in C programming

Structure is commonly referred to as a user-defined data type. C’s structures allow you to store multiple variables of any type in one place (the structure). A structure can contain any of C’s data types, including arrays and other structures. Each variable within a structure is called a member of the structure. They can hold any number of variables, and you can make arrays of structures. This flexibility makes structures ideally useful for creating databases in C. Similar to the structure there is another user defined data type called Union which allows the programmer to view a single storage in more than one way i.e., a variable declared as union can store within its storage space, the data of different types, at different times. In this unit, we will be discussing the user-defined data type structures and unions.

Structures are a way of grouping homogeneous data together. But it often happens that at any time we require only one of the member’s data. For example, in case of the support price of shares you require only the latest quotations. And only the ones that have changed need to be stored. So if we declare a structure for all the scripts, it will only lead to crowding of the memory space. Hence it is beneficial if we allocate space to only one of the members. This is achieved with the concepts of the UNIONS.

 UNION in C Programming

UNIONS are similar to STRUCTURES in all respects but differ in the concept of storage space. A UNION is declared and used in the same way as the structures. Yet another difference is that only one of its members can be used at any given time. Since all members of a Union occupy the same memory and storage space, the space allocated is equal to the largest data member of the Union. Hence, the member who has been updated last is available at any given time.

 

C program example for UNION

Write a program to illustrate the concept of union.

/* Declare a union template called tag */

union tag {

int nbr;

char character;

}

/* Use the union template */

union tag mixed_variable;

/* Declare a union and instance together */

generic_type_tag {

char c;

int i;

float f;

double d;

} generic;

3(a) Write a program in C, using structures to generate a report for employees which displays the total salary, designation, department, address etc. Assumptions can be made wherever necessary. 8m Jun2008

Solved program can be found on this link http://cssimplified.com/assignments/an-interactive-c-program-to-generate-pay-slips-for-the-staff-of-size-12-employees-2-members-are-clerks-one-computer-operator-6-salesmen-3-helpers-working-in-a-small-chemist-retail-shop