Introduction
अब तक हमने Structures के बारे में सीखा, जहाँ:
- multiple variables को एक साथ store किया जाता है
- हर member के लिए अलग-अलग memory allocate होती है
लेकिन कुछ situations में memory efficient programming की जरूरत होती है, जहाँ:
- हमें एक समय पर केवल एक ही value use करनी होती है
- लेकिन different data types में
उदाहरण:
- एक variable कभी integer हो सकता है
- कभी float
- कभी character
ऐसी situations में Structure inefficient हो जाता है क्योंकि वह हर member के लिए अलग memory लेता है।
इसी problem को solve करने के लिए C language में Union का concept दिया गया है।
Union में:
- सभी members एक ही memory location share करते हैं
- एक समय पर केवल एक member valid होता है
इसलिए Union memory saving के लिए बहुत useful होता है।
Definition
Union एक user-defined data type है जिसमें सभी members एक ही memory location को share करते हैं।
Structure vs Union (Basic Difference)
| Structure | Union |
|---|---|
| हर member के लिए अलग memory | सभी members एक ही memory share करते हैं |
| size = sum of members | size = largest member |
| सभी values एक साथ store हो सकती हैं | एक समय पर केवल एक value valid होती है |
Union Declaration
Syntax
union union_name
{
data_type member1;
data_type member2;
};
Example
union data
{
int i;
float f;
char c;
};
Example 1: Basic Union Program
#include <stdio.h>
union data
{
int i;
float f;
};
int main()
{
union data d;
d.i = 10;
printf("i = %d\n", d.i);
d.f = 5.5;
printf("f = %.1f", d.f);
return 0;
}
Output:
i = 10
f = 5.5
Explanation:
- पहले
i = 10store हुआ - फिर
f = 5.5store हुआ - नई value ने पुरानी value को overwrite कर दिया
Example 2: Value Overwrite Concept
#include <stdio.h>
union data
{
int i;
float f;
};
int main()
{
union data d;
d.i = 10;
d.f = 3.14;
printf("i = %d\n", d.i);
printf("f = %.2f", d.f);
return 0;
}
Output:
i = (garbage value)
f = 3.14
Explanation:
- last assigned value ही valid रहती है
- पहले value overwrite हो गई
Example 3: Size of Union
#include <stdio.h>
union data
{
int i;
float f;
char c;
};
int main()
{
printf("%lu", sizeof(union data));
return 0;
}
Output:
4
Explanation:
- सबसे बड़ा data type = float/int (4 bytes)
- union size = largest member
Example 4: Union with Character
#include <stdio.h>
union data
{
int i;
char c;
};
int main()
{
union data d;
d.i = 65;
printf("%d\n", d.i);
d.c = 'A';
printf("%c", d.c);
return 0;
}
Output:
65
A
Technical Understanding
Union का use इन situations में होता है:
- memory optimization
- embedded systems
- system programming
- different data formats handle करना
Important Points
- Union में memory shared होती है
- एक समय पर एक ही value valid होती है
- size = largest member
- last assigned value ही valid रहती है
Exam Points
- Union = shared memory concept
- Structure vs Union difference important है
- size calculation पूछा जाता है
- overwrite concept important है
- practical programs पूछे जाते हैं