Documente Academic
Documente Profesional
Documente Cultură
#17 union
By Saurabh Shukla | 2017mysirg.com
union
Defining union
union <tag>
{
Type variableName;
Type variableName;
...
};
union is a keyword.
<tag> is any name of your choice. It becomes the name of user defined data type.
Type is any data type
Remember to put semicolon at the end of union body.
You can define a union either inside a function block or outside a function. Former is
known as local definition and later is known as global definition of union. Locally
defined unions can only be used in the body of block. Globally defined unions can be
used anywhere in the program.
Example
union mydata
{
#17 union
C Notes Vol-3 by Saurabh Shukla
www.mysirg.com
int a;
float b;
char c;
};
You can declare union variables either along with the union definition or afterwards.
union mydata
{
int a;
float b;
char c;
}m;
The variable is m of type mydata created along with the union definition. You can also
declare variables any time after defining structure.
union mydata
{
int a;
float b;
char c;
};
int main ()
{
union mydata u1;
}
The variable u1 or m will be large enough to hold the largest of the three types; the specific
size is implementation dependent. Anyone of these types may be assigned to u1 or m and
then used in expressions, so long as the usage is consistent: the type retrieved must be the
type most recently stored. It is the programmers responsibility to keep track of which tye is
currently stored in a union; the results are implementation dependent if something is stored
as one type and extracted as another.
#17 union
C Notes Vol-3 by Saurabh Shukla
www.mysirg.com
To access union member variables you have to use dot (.) operator (member access
operator).The syntax is same as you used in structures.
union mydata
{
int a;
float b;
char c;
};
int main ()
{
union mydata u1;
u1.a=5;
printf(int value = %d,u1.a);
u1.b=3.5;
printf(\nfloat value = %f,u1.b);
u1.c=A;
printf(\nchar value = %c,u1.c);
}
You can store only one value at a time in u1. It shares the same memory space to
store value of mentioned type. So you can access value which is most recently
stored.
#17 union
C Notes Vol-3 by Saurabh Shukla
www.mysirg.com
References:
Lecture 17union in C
o https://youtu.be/IQ_SmLX_Ncc?list=PL7ersPsTyYt2Q-SqZxTA1D-melSfqBRMW
Exercise