×

Union Program in C

 How should a union be defined?

 In C programming, a Union is a method used to organize different data types into groups in the same way that Structures are used. We are able to make user-defined data type elements by utilizing a union.

In contrast to Structures, a C union variable will allot shared memory to all of its members (i.e., book cost, book name, Writer’s name, etc.). The allocated shared memory has a size that is equivalent to that of the biggest union member. We can save a lot of memory (RAM) because of this.

 We are unable to access every union member simultaneously due to this shared memory. The C union variable can only contain one member at a time. Therefore, we can only access one member at a time.

The union is also a grouping of many items with varying properties stored in close proximity to one another in memory. They are custom data types. The structure's components are referred to as the union's members, and the union name (like date, book, etc.) is handled as a data type.

When a union is defined, no memory is allocated. Only after the creation of its variables, memory is allocated (It is typically preceded by the keyword union). Among all of its members, the variables of union types take up the most memory space. Only one of its members may store data at once and concurrently. Using the dot (.) operator, you may access the members.

Difference between Structure and Union

  • In Structure, all the data members are stored in separate memory locations, whereas in Union, all members share the same memory location.
  • A union variable's memory usage is equal to the amount of storage space required by the largest data member of the union, as opposed to a structure variable's memory usage, which equals the total of all the memory of the structure's members.
  • Unlike a structure variable, which contains all members, a union variable can only have one active member at a time.

 Union Syntax in C:

union box
{
     	int x;
     	char y;
     	float z;
};
union box b1;

 In this syntax, we initialized a union named box, which has three data members(int, char, float). Here union is the keyword, and the box is the data type.

Among all these members, the member who is taking the most memory, the box will get the same amount of memory. This indicates that

  • int takes 2-byte memory.
  • Char takes 1-byte memory.
  • Float takes 4-byte memory.

So maximum memory which is allotted to the box will be 4 bytes.

Here b1 is the variable of box data type

 x,y, and z are the member variables.

1. Example Program for C Union:

 
#include<stdio.h>
union box
{
     	int x;
     	char y;
     	float z;
};
void main()
{
     	union box b1;
     	b1.x =3;
     	printf("\n x=%d",b1.x);
     	b1.y='c';
     	printf("\n y=%c",b1.y);
     	b1.z=3.8;
     	printf("\n z=%f",b1.z);
}

Explanation:

  • Union is the keyword, and the box is the data type.
  • b1 variable has three member variables x,y, and z.
  • The dot(.) operator is used to access member variables.
     b1.x =3;   b1.y='c';         b1.z=3.8;
  • For int data type, we use %d format specifier.
  • For char data type, we use %c format specifier.
  • For float data type, we use %f format specifier.

Program Output:

Union Program in C

2-Example for C union Program:

 
#include <stdio.h>
#include <string.h>
 
union student
{
        	char name[15];
         	int age;
        	float percentage;
};
 
int main()
{
    union student data;
 
       printf("Student data is :\n");
       strcpy(data.name, "Durgesh");
       printf("Name : %s \n", data.name);
 
        data.age=18;
       printf("Age: %d \n", data.age);
 
       data.percentage = 87.63;
       printf("Percentage : %f \n", data.percentage);
       return 0;
}

Explanation :

  • “Durgesh” is assigned to union member “data.name”. The memory location name is “data.name” and the value stored in this location is “Durgesh”.
  • Then, “18” is assigned to union member “data.age”. Now, the memory location name is changed to “data.age” with the value “18”.
  • Then, “87.63” is assigned to union member “data.percentage”. Now, the memory location name is changed to “data.percentage” with the value “87.63”.
  • In a similar manner, the name and value of each union member are periodically changed in the communal storage area.
  • As soon as values are assigned to each union member, they may be retrieved.
  • Because all members share the same memory, if we don't access them before giving values to other members, the other members will overwrite the member's name and value.
  • All union members cannot be accessed at once.

Program Output:

Union Program in C

Conclusion: So, we can say that,the union makes memory management easier. Only the most recent value submitted into the union will be available, which is the union's disadvantage. When union members don't need to be accessible at the same time, this method should be utilized.


Related Topics

Stack implementation in C

Stack implementation in C Stack stores the data in a particular order. It is a linear data structure that follows the principle of the Last In First Out (LIFO) technique where...

3 minutes read.

Actual and Formal Parameters

Any variable declared within the parenthesis is referred to as the parameters during the function declaration. Parameters tell the function about the argument datatype, their order, and the number of...

5 minutes read.

What is required in each C Program?

Each C program must require one function, i.e., main() function. It is because when we execute the C program, C compiler looks for the main() function, and from here only...

5 minutes read.

Exit control loop in C

To examine the termination condition for an exit, we usually use an exit control loop in C. If the evaluation for termination condition results in true, then the control would...

3 minutes read.

Formatted Input and output function in C

Formatted I/O functions display multiple outputs to the user by taking various inputs. All data types like int, float, char and double are supported by the formatted I/O function. In...

4 minutes read.

Pseudo Code in C

Pseudo code in C can be referred to as a simple way or method to write programming code or program algorithm in English. A pseudocode is an informal representation of...

4 minutes read.

Run Time Polymorphism in C

What is polymorphism? Polymorphism refers to the existence of various forms. Polymorphism can be simply defined as a message's capacity to be presented in multiple forms. An individual who can have...

4 minutes read.

Break, continue and goto statement in C

Break statement Break statement is used to break the process of a loop (while, do while and for) and switch case. Syntax: break; Example 1 while(test Expression) { // codes if(condition for break){ break; } // codes } Example 2 For(int it, condition,...

1 minute read.

Range of int in C

In this session we know about the rage of the int in C language with the suitable examples and the programs. Firstly, we can learn the range of int: The int is...

3 minutes read.

fgets() function in C

fgets() function is present in standard input and output library i.e, stdio.h library. It is a built-in function or pre-define function. It is used to read the specified stream from...

4 minutes read.

How to include graphics.h in C?

How to include graphics.h in code blocks? Graphics .h is a header that allows drawing lines, rectangles, ovals, arcs, polygons, pictures, and strings on a graphical window by giving access to...

6 minutes read.

Prime Number code in C

Prime Number Programs in C language In this tutorial, we will learn how to check whether the given number is a prime number or not, and how to print all the...

4 minutes read.

Types Of Structures In C

We can normally store elements of the same datatype with the help of an array in C programming. We can store multiple numbers of elements of a character data type...

3 minutes read.

Stdio.h in C

Header files are used to make the programmer’s efforts a lot easier. In order to make the programming simple, there are a number of libraries which are included as predefined...

4 minutes read.

Top Array Keywords in C

Sorting array in C Types of array in C Array of structure in C How do you initialize an array in C Array declaration in C Array of strings in C Multidimensional array in C Reverse array...

1 minute read.

Array Example in C

An array is a collection of similar types of data elements arranged in such a way that any number of values can be assigned to it. It can store values that...

4 minutes read.

Pure Virtual Function in C

Before knowing about the pure virtual function some of the important points about the virtual function in C++ are given below. In c++ the member function that is defined in the...

4 minutes read.

Operators in C

An operator is a special symbol that tells the compiler to perform specific mathematical or logical operations. It is the combination of constants and variables through expressions. Example: int c = a+b*5 Where,...

5 minutes read.

C Switch Statements

Switch-case statement comes under the Selection control statement; there are four types of Control statements Decision-making statements (if, if-else)Selection statements (Switch-case)Iteration statements (for, while, do-while)Jump statements (break, continue, goto) If we want...

4 minutes read.

Round Robin Scheduling in C

Round Robin Scheduling in C Round robin is a CPU (Central Processing Unit) scheduling algorithm designed to share the time systems. It is one of the simplest and easiest scheduling algorithms...

4 minutes read.