Union C Dijelaskan: Definisi, Penggunaan, dan Perbandingan dengan Struktur
Union C Dijelaskan
Pelajari cara mendefinisikan, membuat, dan mengakses union C, dan temukan mengapa mereka berbeda dari struktur dalam tata letak memori dan aplikasi.
A union is a user‑defined type in C that, unlike a struct, can hold only one of its member values at a time. This makes unions ideal for memory‑efficient data representations and type‑punning in low‑level programming.
Mendefinisikan Union
Use the union keyword to declare a new type. For example:
union Car { char name[50]; int price; };
The above code creates a derived type union Car that can store either a 50‑character string or an integer price.
Membuat Variabel Union
Defining a union does not allocate memory. To use it, declare variables of that type:
union Car car1, car2, *car3;
Alternatively, you can combine the definition and variable declaration:
union Car { char name[50]; int price; } car1, car2, *car3;
In both examples, car1 and car2 are union instances, while car3 is a pointer to a union.
Mengakses Anggota Union
Use the dot (.) operator for direct access and the arrow (->) for pointer access:
car1.price – accesses the price field of car1. car3->price or (*car3).price – accesses price via a pointer.
Union vs. Structures
While structs allocate enough space for all members, a union’s size equals the size of its largest member. Consider this comparison:
#include <stdio.h> union UnionJob { char name[32]; float salary; int workerNo; } uJob; struct StructJob { char name[32]; float salary; int workerNo; } sJob; int main() { printf("size of union = %zu bytes\n", sizeof(uJob)); printf("size of structure = %zu bytes", sizeof(sJob)); return 0; }
Output:
size of union = 32 size of structure = 40
Here, the struct occupies 40 bytes (32 + 4 + 4), while the union occupies only 32 bytes – the size of its largest member, name[32]. All union members share the same memory region.
Contoh Praktis: Penimpaan Anggota
#include <stdio.h> union Job { float salary; int workerNo; } j; int main() { j.salary = 12.3; j.workerNo = 100; // overwrites the previous value printf("Salary = %.1f\n", j.salary); printf("Number of workers = %d", j.workerNo); return 0; }
Output:
Salary = 0.0 Number of workers = 100
Because salary and workerNo share the same memory, writing to one clears the other.
To explore real‑world use cases, read Why do we need C Unions?.