Saturday, 31 August 2013

Union | C Programming Language Tutorial pdf



Union:-

Union is a data type in „C? which allows an ruelay of more than none Var in the same memory arc i.e. using the memory space for different van at same place.
Syntax:-
union uni-name
{
type Var 1;
type Var 2;
}< union Var> ;
All var inside an union share storage space. The compiler will allocate sufficient storage for the union var to accommodate the largest element in the union .Other element of the union use the same space (as it is using same space) it is different from structures.

Declining var & pointer to unions:-
union name
{
char name [40];
char id [20];
} id *ptr 2;

Difference b/w structures & unions:
structure
{
char name [25]
Int idno;
float sal;
} emp;
union
{
char name [25]
Int idno;
float sal;
} desc;
void main()
{
printf (“ size of struct is %d” size of ( emp));
printf (“size of union is %d”, size of (desc));
}

Operations on union members:
Only one member of a union can be accessed at a time i.e. because at every instance only one of the union var. will have a meaningful value, only that var is read.

Operations an unions:-
Unions have all the features provided y a Structure which are a conveyance of memory sharing properties of a union. This is evident by the following operations union which are legal.
1. Union var. can be assigned to another union var
2. Union Var can be passed to a function as parameters.
3. The address of the union var. can be extracted by using address of operator.
4. A function can accept & retune a union of a ptr to a union

Scope of a Union:
void main ( )
{
union
{
int i;
char c;
float f;
};
printf { “ i = % d”, i);
}

Output:-
/* compiler dependent* /

Fields in structure:
To allocate memory in bits. Bit fields are treated as unsigned integers
Syntax:-
structure <tag>
{
unsigned <var> : value ;/*rep of bit fields */
};

Ex:
structure with_bits
{
unsigned first :5;
unsigned second :9;
};
Total 14, but it goes to 16 as we can?t have 14 bit memory
void main ( )
{
Union
{
int i ;
};
i = 0;/*second =0 */
b. first =9; /* second =0*/
}

0 comments:

Post a Comment

 

C Programming Language Interview Questions and Answers Tutorial for beginners. Copyright 2013 All Rights Reserved