0
0
C++programming~5 mins

Structure vs union comparison in C++

Choose your learning style9 modes available
Introduction

Structures and unions help group different data types together. They let you keep related information in one place.

When you want to store multiple related values together, like a person's name and age.
When you need to save memory by sharing space for different data types, but only use one at a time.
When you want to organize data clearly for easier understanding and maintenance.
When you want to pass multiple values as one unit to functions.
When you want to model real-world objects with different properties.
Syntax
C++
struct StructName {
    type1 member1;
    type2 member2;
    // more members
};

union UnionName {
    type1 member1;
    type2 member2;
    // more members
};

A structure stores all members separately, each with its own space.

A union stores all members in the same memory space, so only one member can hold a value at a time.

Examples
This structure stores a name and age separately for each person.
C++
struct Person {
    char name[20];
    int age;
};
This union can hold an int, a float, or a string, but only one at a time.
C++
union Data {
    int i;
    float f;
    char str[20];
};
Sample Program

This program shows how a structure keeps all data separately, while a union shares memory for all members. Changing one union member affects others.

C++
#include <iostream>
#include <cstring>

struct Person {
    char name[20];
    int age;
};

union Data {
    int i;
    float f;
    char str[20];
};

int main() {
    Person p1;
    strcpy(p1.name, "Alice");
    p1.age = 30;

    std::cout << "Structure Person:\n";
    std::cout << "Name: " << p1.name << "\n";
    std::cout << "Age: " << p1.age << "\n\n";

    Data d;
    d.i = 10;
    std::cout << "Union Data after setting int: " << d.i << "\n";
    d.f = 220.5f;
    std::cout << "Union Data after setting float: " << d.f << "\n";
    strcpy(d.str, "Hello");
    std::cout << "Union Data after setting string: " << d.str << "\n";

    std::cout << "Union Data int now: " << d.i << " (may be garbage)\n";

    return 0;
}
OutputSuccess
Important Notes

Structures use more memory because each member has its own space.

Unions save memory but only one member can be used at a time.

Accessing a union member different from the last one set can cause unexpected values.

Summary

Structures store all members separately and keep all values.

Unions share memory among members and only one value is valid at a time.

Use structures for grouping related data, and unions to save memory when only one value is needed at a time.