0% found this document useful (0 votes)
24 views7 pages

E-Note 30037 Content Document 20241231023132PM

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views7 pages

E-Note 30037 Content Document 20241231023132PM

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Unions in C

Introduction

• Definition: Unions are user-defined data types in C that allow storage of different
data types in the same memory location.
• Similarity to structures: Like structures, unions allow the grouping of variables,
but with a key difference.

The storage associated with a union variable is the storage required for the largest
member of the union.
When a smaller member is stored, the union variable can contain unused memory
space.
All members are stored in the same memory space and start at the same address.
Hence, the stored value is overwritten each time a value is assigned to a different
member.
Begin the declaration of a union with the union keyword, and enclose the member
list in curly braces.
Basic Syntax
union SampleUnion
{
int integer;
float floating_point;
char character;
};
Example
int main( )
#include <stdio.h> {
#include <string.h> union Example e1;
union Example e1.i = 10;
{ printf( "e1.i : %d\n", e1.i);
int i; e1.f = 220.5;
float f; printf( "e1.f : %f\n", e1.f);
char str; e1.str='a';
}; printf( "e1.str : %c\n", e1.str);
}
Memory Representation

Example

float f e1.f

int i e1.i
char str e1.str
Memory Allocation

• Memory size: Determined by the largest member of the union.


• Shared memory: All members of the union share the same
memory location.
Differences between Structure and Union

You might also like