- C Programming Tutorial
- C - Home
- Basics of C
- C - Introduction
- C - Features
- C - Basics
- C - History
- C - Structure of C Program
- C - Program Structure
- C - Hello World
- C - Compilation Process
- C - Comments
- C - Tokens
- C - Keywords
- C - Identifiers
- C - User Input
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Integer Promotions
- C - Type Conversion
- C - Type Casting
- C - Booleans
- Constants and Literals in C
- C - Constants
- C - Literals
- C - Escape sequences
- C - Format Specifiers
- Operators in C
- C - Operators
- C - Arithmetic Operators
- C - Relational Operators
- C - Logical Operators
- C - Bitwise Operators
- C - Assignment Operators
- C - Unary Operators
- C - Increment and Decrement Operators
- C - Ternary Operator
- C - sizeof Operator
- C - Operator Precedence
- C - Misc Operators
- Decision Making in C
- C - Decision Making
- C - if statement
- C - if...else statement
- C - nested if statements
- C - switch statement
- C - nested switch statements
- Loops in C
- C - Loops
- C - While loop
- C - For loop
- C - Do...while loop
- C - Nested loop
- C - Infinite loop
- C - Break Statement
- C - Continue Statement
- C - goto Statement
- Functions in C
- C - Functions
- C - Main Function
- C - Function call by Value
- C - Function call by reference
- C - Nested Functions
- C - Variadic Functions
- C - User-Defined Functions
- C - Callback Function
- C - Return Statement
- C - Recursion
- Scope Rules in C
- C - Scope Rules
- C - Static Variables
- C - Global Variables
- Arrays in C
- C - Arrays
- C - Properties of Array
- C - Multi-Dimensional Arrays
- C - Passing Arrays to Function
- C - Return Array from Function
- C - Variable Length Arrays
- Pointers in C
- C - Pointers
- C - Pointers and Arrays
- C - Applications of Pointers
- C - Pointer Arithmetics
- C - Array of Pointers
- C - Pointer to Pointer
- C - Passing Pointers to Functions
- C - Return Pointer from Functions
- C - Function Pointers
- C - Pointer to an Array
- C - Pointers to Structures
- C - Chain of Pointers
- C - Pointer vs Array
- C - Character Pointers and Functions
- C - NULL Pointer
- C - void Pointer
- C - Dangling Pointers
- C - Dereference Pointer
- C - Near, Far and Huge Pointers
- C - Initialization of Pointer Arrays
- C - Pointers vs. Multi-dimensional Arrays
- Strings in C
- C - Strings
- C - Array of Strings
- C - Special Characters
- C Structures and Unions
- C - Structures
- C - Structures and Functions
- C - Arrays of Structures
- C - Self-Referential Structures
- C - Lookup Tables
- C - Dot (.) Operator
- C - Enumeration (or enum)
- C - Structure Padding and Packing
- C - Nested Structures
- C - Anonymous Structure and Union
- C - Unions
- C - Bit Fields
- C - Typedef
- File Handling in C
- C - Input & Output
- C - File I/O (File Handling)
- C Preprocessors
- C - Preprocessors
- C - Pragmas
- C - Preprocessor Operators
- C - Macros
- C - Header Files
- Memory Management in C
- C - Memory Management
- C - Memory Address
- C - Storage Classes
- Miscellaneous Topics
- C - Error Handling
- C - Variable Arguments
- C - Command Execution
- C - Math Functions
- C - String Functions
- C - Static Keyword
- C - Random Number Generation
- C - Command Line Arguments
C Programming - C Unions
![]() Share with a Friend |
C Programming - C Unions
C Unions
A union in C is a special data type that allows storing different data types in the same memory location. A union can hold one of its members at a time, meaning all the members share the same memory space. This allows for efficient memory usage, as the memory used by a union is only the size of its largest member.
Syntax of Union
C
union union_name {
data_type1 member1;
data_type2 member2;
// more members
};
- union_name: The name of the union (optional, can be omitted when using anonymous unions).
- data_type: The type of the member.
- member: The variable name.
Memory Allocation in Unions
- Memory Size: The size of a union is determined by the size of its largest member.
- Memory Sharing: All members share the same memory space. At any given time, only one member can hold a value, and writing to one member will overwrite the value of the other members.
Example: Union Declaration and Usage
C
#include <stdio.h>
union data {
int i;
float f;
char c;
};
int main() {
union data d;
d.i = 10; // Assigning value to the integer member
printf("i: %d\n", d.i);
d.f = 3.14; // Assigning value to the float member
printf("f: %f\n", d.f);
d.c = 'A'; // Assigning value to the character member
printf("c: %c\n", d.c);
return 0;
}
Output:
i: 10
f: 3.140000
c: A
Explanation:
- The union data has three members: an integer (i), a float (f), and a character (c).
- Each time we assign a value to one member, the previous value stored in the union is overwritten since all members share the same memory location.
- When we print the value of i, f, and c, we get the value of the most recently assigned member.
Size of a Union
The size of a union is the size of its largest member, but it may also include some padding to align the data properly in memory.
Example: Size of a Union
C
#include <stdio.h>
union data {
int i;
float f;
char c;
};
int main() {
union data d;
printf("Size of union: %zu\n", sizeof(d)); // Prints the size of the union
return 0;
}
Output:
Size of union: 4
Explanation:
- In this case, the size of the union is 4 bytes because the largest member (int) requires 4 bytes of memory.
Accessing Union Members
A union member can be accessed using the dot (.) operator, similar to structures. However, only one member can hold a value at a time.
Example: Accessing Union Members
C
#include <stdio.h>
union data {
int i;
float f;
char c;
};
int main() {
union data d;
d.i = 100; // Assigning value to integer member
printf("i: %d\n", d.i);
d.f = 98.76; // Assigning value to float member
printf("f: %.2f\n", d.f);
d.c = 'Z'; // Assigning value to character member
printf("c: %c\n", d.c);
return 0;
}
Output:
i: 100
f: 98.76
c: Z
Explanation:
- Each member of the union holds a separate value, but only the most recently assigned value is valid.
- As we assign values to i, f, and c, the previous value is overwritten.
Union vs. Structure
| Feature | Union | Structure |
|---|---|---|
| Memory Usage |
Members share the same memory location (size of the largest member) |
Each member has its own memory location |
| Access |
Only one member can store a value at a time |
All members can store a value simultaneously |
| Size |
Size of the largest member |
Size of all members combined |
Applications of Unions
Unions are useful in situations where:
- Memory Optimization: Unions save memory, as they allow storing different types of data in the same memory location.
- Multitype Data: Unions are commonly used in situations where a variable can take multiple types, but only one type is used at any given time. For example, in embedded systems, where memory is limited.
- Working with Different Formats: They are useful in situations like working with different data formats in file handling, network protocols, or device drivers.
Example: Union for Multitype Data
C
#include <stdio.h>
union data {
int i;
float f;
char c;
};
void printData(union data d, int type) {
switch (type) {
case 1: printf("Integer: %d\n", d.i); break;
case 2: printf("Float: %.2f\n", d.f); break;
case 3: printf("Character: %c\n", d.c); break;
default: printf("Invalid type\n"); break;
}
}
int main() {
union data d;
d.i = 5;
printData(d, 1); // Print integer
d.f = 3.14;
printData(d, 2); // Print float
d.c = 'X';
printData(d, 3); // Print character
return 0;
}
Output:
Integer: 5
Float: 3.14
Character: X
Explanation:
- This example demonstrates how a union can store data of different types (integer, float, character) at different times, and a function can print the stored value based on the type.
Conclusion
- Unions in C are a powerful tool for efficiently managing memory, especially when you need to store one of several possible data types at a time.
- While they share the same memory for all members, unions help reduce memory usage by allocating space only for the largest member.
- Unions are useful for situations involving multitype data or when memory optimization is important, such as in embedded systems or handling different data formats.
