Union in C

Union is same like as structure. Union is a one concept that used to create our own data type or you can say user define data type. Simply we use the union to create the different user define data type. Each element in a union is called member. In union memory utilization is proper.

Union size is not fixed. It's depends on number of data types in union. In union we can create multiple data types. All data value store in highest data member memory.

Syntax of Union:

Union syntax is same as structure syntax. Only keyword is different.


    union union_name
    {
    data_types variable_name1;
    data_types variable_name2;
    data_types variable_n;
    }union_variable_name;
    	

How many ways we can create union variable in C?

In three ways we can create union variables in C.

Example: union variable_name declaration inside the terminating semi column.


    union book
    {
    char bname[20];
    int pages;
    float price;
    }b;

Example: union variable_name declaration outside the terminating semi column.


    union book
    {
    char bname[20];
    int pages;
    float price;
    };
    
    union book b;

Example: union variable_name declaration inside the main() function.


    union book
    {
    char bname[20];
    int pages;
    float price;
    };
    
    void main()
    {
    union book b; //union variable declaration inside the main() function.
    }

When union allocate the memory?

When we declare the variable of union then memory allocated to union user define data type. All data store in highest memory location in union which data member have highest size. In union data store in same memory location.

Example: of union program with inside the terminating semi column:


    #include<stdio.h>
    #include<conio.h>
    #include<string.h>

	union book
	{
		char bname[20];
		int pages;
		float price;
	}b;

	void main()
	{

		clrscr();
		strcpy(b.bname,"Campuslife");
		b.pages=650;
		b.price=500.00;
		printf("Book Name:- %s",b.bname);
		printf("\nBook Pages:- %d",b.pages);
		printf("\nBook Price:- %f",b.price);
	
    	getch();
	}

Ouput:


    Book Name:- Campuslife
    Book Pages:- 650
    Book Price:- 500.0000

Example of union program with outside the terminating semi column:


	#include<stdio.h>
	#include<conio.h>
	#include<string.h>

	union book
	{
		char bname[20];
		int pages;
		float price;
	};
	
	union book b;
	void main()
	{

		clrscr();
		strcpy(b.bname,"Campuslife");
		b.pages=650;
		b.price=500.00;
		printf("Book Name:- %s",b.bname);
		printf("\nBook Pages:- %d",b.pages);
		printf("\nBook Price:- %f",b.price);
	
    	getch();
	}

Output:


    Book Name:- Campuslife
    Book Pages:- 650
    Book Price:- 500.0000

strcpy() function definition

In above program we used strcpy() function to store the string or character value. Without strcpy() function you cannot store the string or character value.

Post Your Comment