Topic :Structure Vs Union in C++: Union declaration | Union Initializing | Structure Vs Union:

Structure Vs Union:

structure and union

A Structure (Struct) is used to define a data type with several fields. Each field takes up a separate storage location. For Example the structure



struct Disk 
{ 
   int S-width; 
   int S-height; 
};


Appears in Memory as shown in above figure:

A Union is similar to a structure, however it defines a single location that can be given many different field names.



union Disk 
{ 
   int U-width; 
   int U-height; 
};


The U-Width and U-Height share the same space, as shown in above figure. we might think of a structure as a large box divided up into several different compartments, each with its own name. A union is a box, not divided at all, with several different labels placed on the single compartment inside. in a structure, the fields do not interact. Changing one field does not change any others. in a union, all fields occupy the same space, so only one may be active at a time. in other words, if we put something in U-Width, assigning something to U-height wipes out the old value of U-width.



Union declaration:

The concept of union in C/C++ is: if we have something in the Memory, is there only one way to access that memory location or there are other ways to access it. We have been using int and char interchangeably in our programs. We have already developed a program that prints the ACSII codes. In this program, we have stored a char inside an integer. Is it possible to have a Memory location and use it as int or char interchangeable ? for such purposes, the construct Union is used. The syntax of Union is:


union Union_Tag 
{ 
   Data-Type1 Element1;
   Data-Type2 Element2;
   Data-Type3 Element3;
   .
   .
   Data-TypeN ElementN;
 
}  Union_Object;


The Semicolon after the closing curly brace in the Union definitions is important. Our program will not compile without it. Unfortunately, this semicolon is easy to forget, because when closing curly braces appear in other places in C++ Programs (For Example, at the end of the function). they are seldom followed by a semicolon.


Where Union_Tag is a Name for the model of the structure type and the Optional Parameter Union_Object is a valid identifier for structure object instantiations. Within curly brackets { } they are the types and their sub-identifiers corresponding to the elements that compose the structure.

We Need to Name Union_Tag our self, using the same Naming rules for variables. If we give the intOrChar Union a Union_tag named intOrChar, we are informing C++ that the tag called "intOrChar" looks like an character Arrays, having some variables with different data type.



No Memory is reserved for Union tags. A union is our own data type. C++ does not reserve Memory for the integer data type until we declare an integer variable, same like that C++ does not reserve Memory for a structure until we declare a structure variable.



If the Union Definition includes the parameter intOrChar that parameter becomes a valid type name equivalent to the structure, as shown in the given example.



union intOrChar 
{ 
   int i; 
   char c ; 
};


The Syntax is similar as that of structure. In structures, we have different data Members and all of these have their own Memory space. In Union, the Memory location is same while the first data Member is one name for that Memory location. However, the second data member is another name for the same location and so on. Consider the above Union (i.e. intOrChar) that contains an integer and a character as data Members. What will be the size of this Union ? The Answer is the very simple. The Union will be allocated the Memory equal to that of the largest size data Member. If the int occupies four bytes on our system and char Occupies one byte, the Union intOrChar will occupy four bytes.



Initializing Union Data:

Same Like Structure, we can use Dot ( . ) Operator to Access any Member of a Union. Once we have declared our some objects of a determined union intOrChar we can Operate with the fields that form them. to do that we have to use a point (.) inserted between the object name and the field name. Let's have an Example so Know how Union Exactly work.

Suppose we have some integer value 123 and want to append 456 to it so that it becomes 123456. How can we do that ? to Obtain this result, we have to shift the integer three decimal places i.e. we can multiply the integer by 1000 (i.e. 123000) and then add 456 to it (i.e. 123456). Consider a union containing four characters and an integer. Now the size of the char is 1 and integer is 4so the size of the union will be four. we assign the character 'a' to the integer and display the chars and integer value. if we want to shift the value of the first byte into the second byte, the integer will be multiplied by 256 (i.e. A byte contains 8 bits and 2 to power 8 is 256) then add character 'b' to it. we see that the char variables of union contains 'a' and 'b'.



/* This program uses a union of int and char and display
   the memory usage of both - InfoBrother*/
 
#include <iostream>
using namespace std;
 
main()
{
 
	union intOrChar // Declaration of union;
	{
    	   char c[4];
    	   int x;
	}u1; //Declaration of Union_Object;
 
	u1.x = 'a'; // Assigning ‘a’ to x
 
	// Displaying the char array and integer value
	cout << "The value of c = " << u1.c[0] << "," << u1.c[1]
	     << "," << u1.c[2] << "," << u1.c[3]<< endl;
 
	cout << "The value of x = " << u1.x << endl;
 
	// Shifting the values one byte and adding ‘b’ to the int
	u1.x *= 256;
	u1.x += 'b';
 
	// Displaying the char array and integer value
	cout << "The value of c = " << u1.c[0] << "," << u1.c[1]
	     << "," << u1.c[2] << "," << u1.c[3]<< endl;
	cout << "The value of x = " << u1.x << endl;
 
	// Shifting the values one byte and adding ‘b’ to the int
	u1.x *= 256;
	u1.x += 'c';
 
	// Displaying the char array and integer value
	cout << "The value of c = " << u1.c[0] << "," << u1.c[1]
	     << "," << u1.c[2] << "," << u1.c[3]<< endl;
	cout << "The value of x = " << u1.x << endl;
 
	// Shifting the values one byte and adding ‘b’ to the int
	u1.x *= 256;
	u1.x += 'd';
 
	// Displaying the char array and integer value
	cout << "The value of c = " << u1.c[0] << "," << u1.c[1]
	     << "," << u1.c[2] << "," << u1.c[3]<< endl;
	cout << "The value of x = " << u1.x << endl;
 
	return 0;
}


Unions are very rarely used. They become very important when we want to do some super efficient programming. Experiment with the unions and structures.

We have learnt how to use structures and unions. These are relatively less used parts of C/C++ language. But structures at least are very useful. They allow us a convenient way of grouping data about a single entity. We can think of a car or any other object and find out its properties before grouping them in a structure. We Don't Need to manipulate its properties individually as grouping them into a unit is a better option. Try to write different programs using structures.



Difference Between Structure and Union:

Differences between structure and union in C/C++ presented in the table below. Structure and union are different in some ways yet they are conceptually same and have following similarities too.


  • » Both are container data types and can contain objects of any type, including other structure and unions or Array as their Members.
    » Both Structure and unions support only assignment " = " and sizeof Operators.
    » In particular, structures and unions cannot appear as operands of the equality ( == ), inequality ( != ) or typecast operators. The two structure or unions in the assignment must have the same members and members types.
    » Both structure and union can be passed by value to function by value by functions. The Argument must have the same type as the function parameter. A structure or union is passed by value just like others variable: that is, the entire structure or union is copied into the corresponding parameter.



Difference between Structure and Union in C/C++:
Structure Union
The Keyword "Struct" is used to declare a structure.The Keyword "Union" is used to declare a Union.
When a variable is associated with a structure, the compiler allocates the Memory for each Member. the Size of structure is greater than or equal to the sum of sizes of its Members. The smaller Members may end with unused stack bytes.When a Variable is accociated with a union, the compiler allocates the Memory by considering the size of the largest Memory, so size of the union is equal to the size of largest Member.
Each Memory within a Structure is Assigned Unique Storage area of location.Memory allocated is shared by individual Members of union.
The Address of each Member will be in ascending order. This indicates that Memory for each Member will start at different offset values. The address is same for all the Members of a union. this indicates that every Member begins at the same offset valve.
Individual Member can be accessed at a time. Only one Member can be accessed at a time.
Several Members of a structure can initialize at once.Only the first Member of a union can be initialized.
Manipulations of one Member will not affect the values of any others in any way unless they are Operated on in code to do so. The Manipulations of one can affect the others, like if another element is stored before the first is retrieved, the first stored value will lost.
All data Members in a Structure are active at time. Only one data Member is active at a time.








I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement