Understanding `Struct
` and `Union
` in C: A Simple Guide
In C programming, structs and unions are powerful tools for organizing and managing data. They provide a way to group variables of different data types under a single name, making your code more structured and readable.
Structs in C
A struct is like a container that allows you to group variables of different types under one umbrella.
struct Person {
char name[50];
int age;
float salary;
};
Pros:
- Organized Data: Structs help in organizing related data into a cohesive unit. In the above struct,
Person
is a cohesive unit that combines a person's name, age, and salary.. - Readability: Improve code readability by providing a meaningful structure.
- Memory Allocation: Memory is allocated separately for each member.
Cons:
- Memory Overhead: Each member has its memory space, potentially leading to memory wastage.
- Limited Features: Limited flexibility compared to other complex data structures(I mean Arrays, Linked Lists, Queues and Stacks, Trees and Graphs, Hash Tables, …).
#include <stdio.h>
#include "string.h"
struct Person {
char name[50]; // this member has its memory own space: 50*1byte = 50bytes
int age; // 4bytes
float salary; // 4bytes
};
int main() {
struct Person employee;
// Assigning values
strcpy(employee.name, "Saeed");
employee.age = 30;
employee.salary = 50000.00;
// Displaying information
printf("Name: %s\n", employee.name);
printf("Age: %d\n", employee.age);
printf("Salary: %.2f\n", employee.salary);
return 0;
}
Unions in C
A union is a space-efficient construct that allows storing different data types in the same memory location.
Pros:
- Memory Efficiency: Unions save memory by sharing the same memory location for different members.
- Versatility: Useful in situations where only one type of data is needed at a time.
Cons:
- Data Integrity: No type checking; it’s the programmer’s responsibility to keep track of which member is currently valid.
- Limited Use Cases: Typically suitable for specific scenarios where you need to save memory.
#include <stdio.h>
#include "string.h"
// Define a union named Data
union Data {
int intValue;
float floatValue;
char stringValue[20];
};
int main() {
// Create an instance of the union
union Data myData;
// Assign an integer value
myData.intValue = 42;
printf("Value as Int: %d\n", myData.intValue);
// Assign a floating-point value
myData.floatValue = 3.14;
printf("Value as Float: %f\n", myData.floatValue);
// Assign a string value
strcpy(myData.stringValue, "Hello, Union!");
printf("Value as String: %s\n", myData.stringValue);
return 0;
}
Conclusion
structs
and unions
offer different ways to manage data in C. Structs are great for organizing related information, while unions shine in scenarios where memory efficiency is critical. Choose wisely based on your program’s specific requirements.