C language में Union एक user-defined data type होता है जो हमें एक ही memory location पर अलग-अलग types के data store करने की सुविधा देता है। Structure की तरह दिखने वाला यह feature memory efficiency के लिए काफी उपयोगी होता है।
union UnionName {
dataType1 member1;
dataType2 member2;
...
};
जैसे:
union Data {
int i;
float f;
char str[20];
};
यहाँ, Data
एक union है जिसमें तीन members हैं: i
, f
और str
।
विशेषता | Structure | Union |
---|---|---|
Memory Allocation | हर member के लिए अलग-अलग memory | सभी members के लिए एक ही memory |
Access | सभी members को एक साथ access कर सकते हैं | एक समय में केवल एक ही member valid होता है |
Memory Size | सभी members का total size | सबसे बड़े member का size |
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main() {
union Data data;
data.i = 10;
printf("Integer: %d\n", data.i);
data.f = 220.5;
printf("Float: %.2f\n", data.f);
strcpy(data.str, "Hello Union");
printf("String: %s\n", data.str);
return 0;
}
Integer: 10
Float: 220.50
String: Hello Union
data.i
को assign किया गया और print किया गया।data.f
assign किया गया जिससे data.i
की value overwrite हो गई।data.str
assign किया गया जिससे पहले के दोनों values invalid हो गए।Anonymous Union वह होता है जिसका कोई नाम नहीं होता और इसे structure के अंदर direct इस्तेमाल किया जाता है।
struct Employee {
int id;
char name[50];
union {
float salary;
int hours;
};
};
अब salary
और hours
को सीधे structure के object से access किया जा सकता है।
मान लीजिए:
union Sample {
int i; // 4 bytes
float f; // 4 bytes
char str[30]; // 30 bytes
};
तो इसका total size 30 bytes होगा, क्योंकि char str[30]
सबसे बड़ा member है।
struct Student {
char name[30];
int id;
union {
int marks;
char grade;
} result;
};
इसमें student की details के साथ उसके result को भी manage किया जा सकता है।
Union एक powerful concept है C programming में, जो memory को efficiently इस्तेमाल करने में मदद करता है। जब आपको एक variable में अलग-अलग data types को handle करना हो और आप एक समय में केवल एक value को ही इस्तेमाल करते हैं, तो Union आपके लिए सही विकल्प है।
इसका सही उपयोग structure की तरह करना और data overwrite से बचना जरूरी है। Practice के माध्यम से आप Union को अच्छे से समझ सकते हैं।