- UNIT-I (Array)
strlen(),strcpy(), strcat() ,strcmp()
Definition
Macro substitution directives
File inclusion directives
Conditional compilation
Bitwise Operators
Shift operators
Masks
Bitfield
Macro substitution directives
File inclusion directives
Conditional compilation
Bitwise Operators
Shift operators
Masks
Bitfield
Union: Definition
Unions can be used to create a data type containing several other data types inside it and we can use an object of that union to access the members inside it.
A union is quite similar to a structure and it can be defined by replacing the keyword ‘struct’ with the keyword ‘union’
declaration for a Union in C:
Union declaration
union classname
{
int a;
char b;
};
name, a and b are the members of the union class name.
Union: Definition
A union is quite similar to a structure and it can be defined by replacing the keyword ‘struct’ with the keyword ‘union’
declaration for a Union in C:
Now we should create an object for the union in order to access the elements inside it. Below is how we can do that:
union classname object;
Here, an object is the union variable name, that will be used to access the union elements.
Accessing Union elements
Union elements can be accessed using dot (.) operator,
use union_variable_name.element_name to access particular element.
object.a= 5;
object.b= 'a';
Till now the union must have looked the same as the structures in C. But there is a great difference between structure and the unions. When we create a structure, the memory allocated for it is based on the elements inside the structure. So if a structure has two elements one int and one char than the size of that structure would be at least 5 bytes (if int takes 4 bytes and 1 byte is for char).
In case of the union the size of memory allocated is equal to the size of the element which takes the largest size.
So for the union above the size would be only 4 bytes, not 5 bytes.
Take the below example:
union classname
{
int a;
char s;
char t;
};
In this case, if we create the object
union classname object;
Size of this object should be 4 bytes only. This feature of unions gives some benefits but care should be taken while operating with unions. Since the memory allocated is equal to the largest element in the union, values will be overwritten.
Take the below example for better understanding:
#include<stdio.h>
union classname
{
int a;
char s;
char t;
};
union classname object;
int main()
{
object.a=0xFFFF;
printf("%x\n",object.a);
return 0;
}
Output
ffff
Advertisements
कोई टिप्पणी नहीं:
एक टिप्पणी भेजें