Pr.Pg Next Pg

Unions tutorials

  • Union is another example of derived data type of C.

  • The declaration and definition of union is similar to that of structures except the keyword union is used.

  • However the members of the union share the same memory i.e. the members overlay the same memory area

  • In union the compiler allocates the sufficient storage (largest of one of the members) for the union variable to accommodate the largest element of the union, this is how the structure differs the union.

  • Individual variables in a union occupy the same space. Thus writing into one will overwrite the other.

  • Elements of a union are accessed in the same manner as that of the elements of the structures.

  • At the end of the union variables definition only the variable having the largest data storage can be accessed.

 

 

Example: Program to illustrate a union

 Sam Madam

#include<stdio.h>

#include<conio.h>

#include<string.h>

union student

{

int rollno;

char name[20];

float fees;

};

 

void main()

{

student s1;

s1.rollno=15;

printf("Roll no of student : %d",s1.rollno);

strcpy(s1.name,"SAM");

printf("\nName of the student : %s",s1.name);

s1.fees=45000;

printf("\nFees paid by the student : %f",s1.fees);

printf("\nRoll no of student : %d",s1.rollno);

printf("\nName of the student : %s",s1.name);

printf("\nFees paid by the student : %f",s1.fees);

getch();

}

Output

Roll no of student : 15

Name of the student : SAM

Fees paid by the student : 45000.000000

Roll no of student : -14336 //Junk

Name of the student : //Junk

Fees paid by the student : 45000.000000 //Retained by the union variable

 

Operations on union variables

  • A union variable can be assigned to another union variable.

  • A union variable can be passed to a function as a parameter.

  • The address of the union variable can be extracted by using the address of operator(&).

  • A function can accept and return a union or a pointer to a union.

  • Arithmetic and logical operations should not be performed on unions as they are illegal.

Note

  • In case all the union members are of the same data types. The union only retains the value of the last variable defined.


Pr.Pg border                                              Next Pg