In this article difference between structure and union we give the information about The size of a structure is the sum of the sizes of the structure members and the size of the union is equal to the size of the largest member in the union.

Difference between Structure and Union:

Sr. No. Structure Union
1 The struct keyword is used to define the structure. Union keyword is used to define union.
2 In this, each member is given a unique memory space. In this all the members share the same memory.
3 If the value of any one data member is changed in the structure, then it does not affect the other data members. If the value of one data member is changed in the union, the value of other data members will also change.
4 In this, more than one member can be accessed at a time. In this, only one member can be accessed at a time.
5 It supports flexible array. It does not support flexible array.
6 example-struct Employee{ int age; char name[50]; float salary;} Union Emp{ int age; char name[50]; float salary; }
7 The size of a structure is the sum of the sizes of the structure members. The size of the union is equal to the size of the largest member in the union.
8 Every structure member gets space in memory. Not every union member gets space in memory.
9 Program:

#include <stdio.h>

struct demo

{

int p;

float q;

char ch;

};

int main( )

{

struct demo st;

st.p = 100;

st.q = 300.2;

st.ch = ‘Z’;

printf(“%d\n”, st.p);

printf(“%f\n”, st.q);

printf(“%c\n”, st.ch);

return 0;

}

O/P:

100

300.2

Z

Program:

#include <stdio.h>

union demo

{

int p;

float q;

char ch;

};

int main( )

{

union demo st;

st.p = 100;

st.q = 300.2;

st.ch = ‘Z’;

printf(“%d\n”, st.p);

printf(“%f\n”, st.q);

printf(“%c\n”, st.ch);

return 0;

}

O/P:

100

300.2

Z

Structure in C Programming:

Struct in C is a user-defined data type. It is used to bind two or more different data types or data structures together into a single type. Structure is created using struct keyword and struct variable is created using struct keyword and struct tag name.

Union in C:

In C Language, Union is a user defined data type by which we store different data types in the same memory location.

Other words, “A union is a data type defined by the user. In this, all the members share the same memory location.”

We can define Union with many elements and each element in it is called a member.

Some More: 

POP- Introduction to Programming Using ‘C’

DS – Data structure Using C

OOP – Object Oriented Programming 

Java Programming

DBMS – Database Management System

RDBMS – Relational Database Management System

Join Now: Data Warehousing and Data Mining 

Leave a Reply

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