Union vs Structure in C
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

Difference Between Union and Structure in C Programming – Complete Guide

📑 On this page:
  • Introduction
  • What is Structure?
  • What is Union?
  • Key Differences (Comparison Table)
  • Memory Allocation - Structure vs Union
  • Program Example
  • Frequently Asked Questions
📚 In this tutorial, you will learn:
  • What is a structure and how it works in C
  • What is a union and how it works in C
  • The key differences between structure and union
  • How memory allocation works for structure and union
  • When to use structure vs union in your programs

Introduction

In this tutorial, we will learn the difference between union and structure in the C programming language.

Both structure and union are user-defined data types in C that allow you to store different types of data together as a single unit. However, they have key differences in how they allocate memory and how you can access their members.

What is a Structure in C?

A structure in C language is a user-defined data type that is used to group logically related items under one single unit or name. The different data items can be accessed by using the single unit.

All the data members or items in a structure are stored in contiguous memory locations. It is used to store items of different data types. Structure has to be declared and defined before using (just like variable declaration before using it in the program).

🔹 Structure Syntax:

struct structure_name {
    data_type member1;
    data_type member2;
    ...
};

Example:

struct employee {
    int empno;
    char ename[20];
    long salary;
};

What is a Union in C?

In the C programming language, a union is also a user-defined data type. A union is a collection of variables of different data types in the same memory location. In a C program, you can define a union with many members at a time, but only one member can contain a value at any given time.

🔹 Union Syntax:

union union_name {
    data_type member1;
    data_type member2;
    ...
};

Example:

union employee {
    int empno;
    char ename[20];
    long salary;
};

Key Differences Between Structure and Union

Difference Between Union and Structure in C programming Language

From the figure, let us understand some of the differences in detail and then let's list out all differences between structure and union in tabular format.

A programmer must use the struct keyword for defining a structure and the same way for defining a union must use the union keyword.

Structure and Union are both user-defined data types and are used to store different types of data together as a single unit.

From the figure, we can understand that the structure occupies separate or individual memory for its members. In other words, a structure does not have a shared memory location for all of its members. The size of a structure is equal to the sum of all its data members. The size occupied by a structure is 28 bytes.

On the other hand, unlike a structure, a union does not have a separate memory location for every member in it. The size of a union is equal to the size of the largest member among all the data members in the union. The size occupied by a union is 20 bytes.

The programmer can access individual or all members of a structure at a time, but in a union, the user can access only one member at a given point of time.

Comparison Table: Structure vs Union

Feature Structure Union
Keyword struct union
Member Access Can access all members at a time Can access only one member at a time
Memory Allocation Separate memory for each member Shared memory - size = largest member
Memory Size Sum of all member sizes Size of the largest member
Memory Location Separate location for each member Shared location for all members
Effect of Modification Changing one member doesn't affect others Changing one member affects all others
Initialization Can initialize multiple members Can initialize only one member at a time
Storage Can store multiple values of different data types Stores only one value at a time for all members

🎯 Quick Summary: Structure = Separate memory for each member. All members can be accessed at once.
Union = Shared memory (largest member size). Only one member can be accessed at a time.

Memory Allocation: Structure vs Union

Structure Memory Allocation:

  • Each member gets its own separate memory location
  • Total size = sum of all member sizes
  • Example: If a structure has an int (4 bytes), char array (20 bytes), and long (8 bytes), total size = 32 bytes
  • All members can be accessed and modified independently

Union Memory Allocation:

  • All members share the same memory location
  • Total size = size of the largest member
  • Example: If a union has an int (4 bytes), char array (20 bytes), and long (8 bytes), total size = 20 bytes
  • Only one member can hold a value at a time

💻 Practice Exercise

Challenge: Write a program that demonstrates the memory size difference between a structure and a union containing the same members.

🔍 Click to Show Solution
#include <stdio.h>

// Structure definition
struct EmpStruct {
    int id;
    char name[20];
    float salary;
};

// Union definition
union EmpUnion {
    int id;
    char name[20];
    float salary;
};

int main() {
    printf("Size of Structure: %lu bytes\n", sizeof(struct EmpStruct));
    printf("Size of Union: %lu bytes\n", sizeof(union EmpUnion));
    
    return 0;
}

/* Sample Output:
Size of Structure: 28 bytes
Size of Union: 20 bytes
*/

Frequently Asked Questions

1. What is the main difference between structure and union?

The main difference is memory allocation. A structure allocates separate memory for each member, while a union allocates shared memory equal to the size of its largest member.

2. Can I access all members of a union at the same time?

No, in a union, only one member can hold a value at a time. Accessing multiple members will give you garbage values because they share the same memory location.

3. When should I use a union instead of a structure?

Use a union when you need to save memory and only one member will be used at a time. Use a structure when you need to store multiple values simultaneously.

4. How is the size of a structure calculated?

The size of a structure is the sum of the sizes of all its members, plus any padding added by the compiler for alignment.

5. Can a structure contain a union and vice versa?

Yes, you can nest a union inside a structure and a structure inside a union. This is useful for creating complex data structures.

💡 Tip: Use structure when you need to store and access multiple values. Use union when you need to save memory and only one value is needed at a time.

📖 Related Tutorials

  • Define Union in C
  • Create and Use Union in C
  • Structure in C - Complete Guide
  • Array vs Structure in C

Previous Topic: -->> Create and Use Union in C   ||   Next topic: -->> Union Examples


📚 Explore More Topics

🗄️ SQL Interview Questions & Answers

SQL SELECT Statement FAQ SQL Restricting & Sorting Data FAQ SQL Group Functions & Aggregated Data FAQ SQL Multiple Tables (JOINs) FAQ SQL Subqueries FAQ SQL DML Statements (Managing Tables) FAQ SQL Indexes, Synonyms & Sequences FAQ SQL DDL (Tables & Relationships) FAQ SQL Views FAQ SQL Indexing Best Practices FAQ SQL Window & Analytic Functions FAQ

🐍 Python Interview Questions & Answers

Python Interview Questions Python Syntax & Variables FAQ Python Data Types FAQ Python If-Else FAQ Python Loops FAQ Python Functions Interview Q Python String Manipulation FAQ Python Lists & Dictionaries FAQ Python Tuples & Sets FAQ Python Exception Handling FAQ Python OOP Interview Questions

☕ Java Interview Questions & Answers

Java Introduction Interview Q Java Development Environment FAQ Java Data Types FAQ Java Control Flow & Operators FAQ Java Basic Input/Output FAQ Java Arrays FAQ Java Strings FAQ Java Methods FAQ Java Basic OOP Concepts FAQ Java Advanced OOP Concepts FAQ Java OOP Best Practices FAQ Java Exception Handling FAQ Java Synchronization FAQ Java Threads & Concurrency FAQ Java Collection Framework FAQ Java File I/O & Serialization FAQ Java Serialization & Deserialization FAQ Java Features FAQ Java Inner & Anonymous Classes FAQ Java Memory Management FAQ Java Packages FAQ Java Wrapper Classes FAQ Java Streams & Lambda FAQ

C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • Conditional Statements
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • Loops Statements
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processing
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.