0
0
Cprogramming~5 mins

Structure vs union comparison

Choose your learning style9 modes available
Introduction

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

When you want to store multiple related values together, like a person's name, age, and height.
When you need to save memory by sharing the same space for different data types, but only one at a time.
When you want to organize data clearly for easier reading and maintenance.
When you want to pass multiple values as one unit to a function.
When you want to handle different types of data in the same memory location depending on the situation.
Syntax
C
struct StructureName {
    dataType1 member1;
    dataType2 member2;
    ...
};

union UnionName {
    dataType1 member1;
    dataType2 member2;
    ...
};

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

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

Examples
This structure stores a person's name, age, and height all at once.
C
struct Person {
    char name[20];
    int age;
    float height;
};
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 values separately, while a union shares memory for all members. Changing one union member overwrites the others.

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

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

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

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

    printf("Structure Person:\n");
    printf("Name: %s\n", p1.name);
    printf("Age: %d\n", p1.age);
    printf("Height: %.1f\n", p1.height);

    union Data d;
    d.i = 10;
    printf("\nUnion Data after setting int: %d\n", d.i);
    d.f = 220.5f;
    printf("Union Data after setting float: %.1f\n", d.f);
    strcpy(d.str, "Hello");
    printf("Union Data after setting string: %s\n", d.str);

    printf("\nNote: After setting string, int and float values are overwritten.\n");

    return 0;
}
OutputSuccess
Important Notes

Structures use more memory because they store all members separately.

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

Accessing a union member that was not last set can give unexpected results.

Summary

Structures store all members separately and keep all data at once.

Unions share the same memory for all members, so only one value is stored at a time.

Use structures when you need to keep all data together, and unions when you want to save memory and only use one value at a time.