What is a Union?
If we are having the less memory to use in our program, for example 64K, we can use a single memory location for more than one variable this is called union.
You can use the unios in the followig locations.
- You can share a single memory location for a variable myVar1 and use the same location for myVar2 of different data type when myVar1 is not required any more.
- You can use it if you want to user, for example, a long variable as two short type variables.
- When you dont know what type of data is to be passed to a function, and you pass union which contains all the possible data types.
Defining a Union
Union can be defined by the keyword union.
union myUnion{ int var1; long var2; };
Here we have defined a union with the name myUnion and it has two members i.e. var1 of type int and var2 of type long
Declaring the Union
We can declare the union in various ways. By taking the above example we can declare the above defined union as.
union myUnion{ int var1; long var2; }newUnion;
So newUnion will be the variable of type myUnion. We can also declare the union as
myUnion newUnion;
Initializing the Union
We can initialize the union in various ways. For example
union myUnion{ int var1; long var2; }newUnion={10.5};
or we can initialize it as
newUnion.var1= 10;
In later stages we can also initialize the var2 as well but this will over write the var1 value. Normally when we declare the union it is allocated the memory that its biggest member can occupy. So here in our example newUnion will occupy the memory which a long type variable can occupy.
No comments:
Post a Comment