Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is a Structure in C?
2.1.
Syntax of Structure
2.2.
Example
3.
What is a Union?
3.1.
Syntax of Union
3.2.
Example
4.
Difference between Structure and Union in C
5.
Example of Structure and Union showing the difference in C
5.1.
Below is an example of a code that depicts the difference between structure and unionImplementation
6.
Similarities between Structure and Union in C++
7.
Advantages of Structure
8.
Disadvantages of Structure
9.
Advantages of Union
10.
Disadvantages of Union
11.
Frequently Asked Questions
11.1.
What is main difference between structure and union?
11.2.
Is structure and union same?
11.3.
Which is better structure or union?
11.4.
What is the difference between size of structure and union?
12.
Conclusion
Last Updated: May 29, 2024
Easy

Difference Between Structure and Union

Introduction

Structures and Unions manage data in different ways. A Structure allocates specific memory for each input, storing multiple values simultaneously. Whereas a Union shares one memory for all inputs, holding only one value at a time. Structures are handy when you need separate storage, while Unions save space by sharing memory.

Difference-between-structure-and-union

In this article we will discuss about Structure and Union user-defined data types and how they differ from each other. We will also discuss its advantages and disadvantages

To know about Fibonacci Series in C++ click here

What is a Structure in C?

A structure is defined as a user-defined data type, which allows the user to create a data type that is used to group items of different data types into a single type. In the case of structure, all the members have different memory locations.

In order to create a structure, the ‘struct’ keyword is used. There are two types of members in structures in C++:

  • Data Members: These are normal C++ variables, a structure can have variables of different data types in C++.
     
  • Member Function:These are normal C++ functions 

Syntax of Structure

struct Structure_Name{
Member1,
Member2,
.
.
.
MemberN,
};

Example

#include<iostream>
using namespace std;

struct rectangle{
    int x; // length
    int y; // width
    int area()
    { return x * y; }
};

int main(){
    struct rectangle r;
    r.x=5; // length 
    r.y=3; // width
    cout<<"Area of rectangle "<<r.area()<<endl;
}


Output

Area of rectangle 15

What is a Union?

A union is also a user-defined data type that allows the user to group different data types into a single type, but the union reserves the same memory location for all its data members.

In order to declare a union in C++, the keyword ‘union’ is used. Just like structure, it too has data members and member functions

Also, see Literals in C.

Syntax of Union

union Union_Name{
Member1,
Member2,
.
.
.
MemberN,
};

Example

#include<iostream>
using namespace std;


union rectangle{
    int x,y; // length, width
};


int main(){
    union rectangle r;
    r.x=5;// assigning only the length
    cout<<"The length of rectangle is "<<r.x<<" and the width is "<<r.y<<endl;
    r.y=3; //assigning only the width, without changing the length
    cout<<"The length of rectangle is "<<r.x<<" and the width is "<<r.y<<endl;
}


Output

The length of rectangle is 5 and the width is 5
The length of rectangle is 3 and the width is 3


Explanation

In the case of union, all the members share the same memory location as a result of which when we assign value to one member of the union, it affects the other members too, because of which when we assign x the value 5, y automatically gets the value 5 and same is the case when we assign y the value 3.

You can try and compile with the help of online c++ compiler.

Difference between Structure and Union in C

 StructureUnion
  1. To declare a Structure the keyword 'struct' is used.
1.To declare a Union the keyword 'union’ is used.
2. The compiler allocates the memory for each member when a variable is associated with a structure. The size of a structure is greater or equal to the sum of the sizes of its members.2. The compiler allocates memory by considering the size of the largest member when a variable is associated with union. The size of the union is equal to the size of the largest Member.
3. Each member within a Structure is assigned a unique storage area of location.3. All the members of the union share the same memory allocated.
4. The address of each member in the structure is in ascending order, that is, memory for each member starts at different offset values.4. The address is the same for all the members of a union, that is, every member begins at the same offset value.
5. Manipulation of one member of structure won't affect the values of any other member5. Manipulation of one member will affect the other members' value in case of union.
6. We can initialize multiple variables at a time.6. Only the first data member can be initialized.
7. A structure allows accessing and retrieving any data member at a time.7. A union allows retrieving only one data member at a time.

You can also read about, cpp abstract class

Example of Structure and Union showing the difference in C

Below is an example of a code that depicts the difference between structure and union
Implementation

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

// Define a structure
struct NinjaStudent {
    char name[50];
    int age;
    float gpa;
};

// Define a union
union NinjaData {
    int i;
    float f;
    char str[20];
};

int main() {
    // Example of a structure
    struct NinjaStudent s1;
    strcpy(s1.name, "Ninja1");
    s1.age = 19;
    s1.gpa = 8.02;

    printf("Name: %s\n", s1.name);
    printf("Age: %d\n", s1.age);
    printf("GPA: %.2f\n", s1.gpa);
    printf("Size of student structure: %ld bytes\n\n", sizeof(struct NinjaStudent));

    // Example of a union
    union NinjaData d1;
    d1.i = 15;
    printf("d1.i = %d\n", d1.i);
    d1.f = 3.14;
    printf("d1.f = %.2f\n", d1.f);
    strcpy(d1.str, "Ninja");
    printf("d1.str = %s\n", d1.str);
    printf("Size of data union: %ld bytes\n\n", sizeof(union NinjaData));

    return 0;
}


Output

Output

Explanation

In the above example, we have defined a ‘struct NinjaStudent’  which contains three members: ‘name’, ‘age’ and ‘gpa’. Next, we declared a variable ‘s1’ of type â€˜struct NinjaStudent’ and initialized its members, and finally printed the values of the members and size of ‘struct NinjaStudent’ type using the ‘sizeof’ operator.

Moving on, we have defined a ‘union NinjaData’ with three members: ‘i’, ‘f’, and ‘str’.We have then declared a variable ‘d1’ of  ‘union NinjaData’  type and initialized its members and printed their values. We can see that when we assign a value to ‘d1.str’, the value of ‘d1.i’ and ‘d1.f’ gets lost. This happens because all three members share the same memory location.

Therefore when we print the size of Union we get 20, while when we print the size of Structure we get 60 as, 50 bytes due to the ‘name’ array + 4 bytes (‘age’ integer) + 4 (‘gpa’, which is a floating-point number) + 2 bytes of padding(it is added by the compiler and may vary depending on the specific implementation and settings of a compiler).

In a union the total size of the union is equal to the size of its largest member, therefore we got an answer as 20 bytes, as it can hold only one value at a time, storing a value in one member of the union will overwrite any previously stored values in the other members.

Also Read - C++ Interview Questions

Similarities between Structure and Union in C++

  • Structure and union both are user-defined data types.
     
  • Structure and union both contain data members and member functions that are to be declared within the parenthesis bracket.
     
  • Data members of structure and union are accessed using their variables along with their member name that is variable_name.member_name.
     
  • Members of both the structure and union can be objects of any type, structure, union, or arrays.
     
  • Structure and union both can be passed by value to functions and returned by the value of functions.

Advantages of Structure

Some of the advantages of a structure are mentioned below:

  • Structures are user-defined data types that help in organizing data.
     
  • Data Structures can be easily accessed and manipulated using structures.
     
  • They allow code reusability and modularity.

Disadvantages of Structure

Some of the disadvantages of a structure are mentioned below:

  • They use a significant amount of memory.
     
  • They are limited in their functionality.
     
  • They cannot perform complex operations like logical or mathematical operations.
     
  • As it requires storage space, it is slower.

Advantages of Union

Add its advantages in bulleted form

Some of the advantages of Union are mentioned below:

  • As different data types share the same memory location, they are designed to optimize memory usage.
     
  • They are easy to use and have the same syntax as structures.
     
  • It occupies less memory.
     
  • They can be used to represent different data types.

Disadvantages of Union

Add its disadvantages in bulleted form

Some of the disadvantages of Union are mentioned below:

  • As different data types share the same memory location in Union, it can result in potential data loss.
     
  • We can use only one union member at a time.
     
  • If Unions are not used properly, they can result in undefined behavior, that may result in an error.

You can also read about, loop and while loop

Frequently Asked Questions

What is main difference between structure and union?

The main difference between a structure and a union is that a structure stores multiple data types of different sizes, while union stores multiple data types of the same size in the same location.

Is structure and union same?

Both structure and union are used to store multiple data types, but they are not the same. They differ in memory usage and data organization,  a structure stores multiple data types of different sizes, while a union stores multiple data types of the same size in the same location.

Which is better structure or union?

Both structure and union have their own advantages and disadvantages. Depending on one’s specific needs, one has to decide which one to choose. Structures are used to store multiple data types of different sizes, while unions are used in optimizing memory usage by storing multiple data types of the same size in the same memory location.

What is the difference between size of structure and union?

The size of a structure is the sum of the sizes of its individual elements, while in union the size is equal to the size of its largest element. In union, all the elements share the same memory location.

Conclusion

In this article, we thoroughly discussed how structure and union are different from each other. We have understood their syntax, declaration,  advantages, and disadvantages. Refer to our other articles to better understand other topics.

You will find straightforward explanations of almost every topic on this platform. You can read more such articles on our platform, Coding Ninjas Studio. So take your learning to the next level using Coding Ninjas. 

Happy Coding!

Live masterclass