Give the syntax for declaring and initializing a union with a suitable example

10 b] Give the syntax for declaring and initializing a union with a suitable example

C Union is also like structure, i.e. collection of different data types which are grouped together. Each element in a union is called member.

  • Union and structure in C  are same in concepts, except allocating memory for their members.
  • Structure allocates storage space for all its members separately.
  • Whereas, Union allocates one common storage space for all its members
  • We can access only one member of union at a time. We can’t access all member values at the same time in union. But, structure can access all member values at the same time. This is because, Union allocates one common storage space for all its members. Wheras Structure allocates storage space for all its members separately.
  • Many union variables can be created in a program and memory will be allocated for each union variable separately.
  • Below table will help you how to form a C union, declare a union, initializing and accessing the members of the union

Syntax:

union tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};

Example :

union student
{
int  mark;
char name[10];
float average;
};

Declaration Of Union:

We use the union keyword to define unions. Here’s an example

union car
{
  char name[50];
  int price;
};

The above code defines a derived type union car.

Example:

#include <stdio.h>
union Job {
   float salary;
   int workerNo;
} j;

int main() {
   j.salary = 12.3;

   // when j.workerNo is assigned a value,
   // j.salary will no longer hold 12.3
   j.workerNo = 100;

   printf("Salary = %.1f\n", j.salary);
   printf("Number of workers = %d", j.workerNo);
   return 0;
}
output:
Salary = 0.0
Number of workers = 100

Leave a Reply

Your email address will not be published. Required fields are marked *