This website includes Education Information like a programming language, job interview question, general knowledge.mathematics

Education log

PageNavi Results No.

Ads

Tuesday, June 23, 2020

define union in c programming with example

Introducation union in c programming:

In this tutorial, you'll learn about unions in C programming. More specifically, how to create unions, access its members and learn the differences between unions and structures.

A union is a user-defined type similar to structs in C except for one key difference. Structs allocate enough space to store all its members wheres unions allocate the space to store only the largest member.

 

Create union variables in c programming:

When a union is defined, it creates a user-defined type. However, no memory is allocated. To allocate memory for a given union type and work with it, we need to create variables.

 

Unions are conceptually similar to structures. The syntax to declare/define a union is also similar to that of a structure. The only differences is in terms of storage. In structure each member has its own storage location, whereas all members of union uses a single shared memory location which is equal to the size of its largest data member.

 

A union is a special data type available in C that allows to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple-purpose.

 

Defining a Union in c programming:

To define a union, you must use the union statement in the same way as you did while defining a structure. The union statement defines a new data type with more than one member for your program. The format of the union statement is as follows

 

Example Union in c programming:

#include <stdio.h>

#include <string.h>

 

union Data {

   int i;

   float f;

   char str[20];

};

 

int main( ) {

 

   union Data data;       

 

   printf( "Memory size occupied by data : %d\n", sizeof(data));

 

   return 0;

}

 


No comments:

Post a Comment