ProAnswers.org

In which situations we use unions and structure,why?

2 Likes

The members of structure can be of different datatypes unlike in arrays…Thus different members can be accessed through a single structure.

Whereas in union, the members share the same allocated memory, thus memory can be saved. The syntax for structure and union is the same, with the exception of the name.

Instead of unions when we use structures and Instead of structure when we use unions and why?

is this Answer or question :slight_smile:

[b]Structure:[/b]


	Structure is a method of packing the data of different types.

	When we require using a collection of different data items of different data types in that situation we can use a structure.

	A structure is used as a method of handling a group of related data items of different data types. 


Example of Using Structure:  




	
		
			
				struct lib_books
				{
				char title[20];
				char author[15];
				int pages;
				float price;
				};struct lib_books, book1, book2, book3; 
		
	



To holds the details of four fields namely title, author pages and price,the keyword struct declares a structure. These are the members of the structures. Each member may belong to same or different data type. The tag name can be used to define the objects that have the tag names structure. The structure we just declared is not a variable by itself but a template for the structure. We can declare the structure variables using the tag name any where in the program. For example the statement, struct lib_books book1,book2,book3; declares the book1,book2,book3 as variables of type struct lib_books each declaration has four elements of the structure lib_books. 



Union:



However the members that we compose a union all share the same storage area within the computers memory where as each member within a structure is assigned its own unique storage area. Thus unions are used to observe memory. They are useful for the application involving multiple members. Where values need not be assigned to all the members at any time. Unions like structure contain members whose individual data types may differ from one another also. Like structures union can be declared using the keyword union as follows: 


	
		
			
				
					union item
					{
					int m;
					float p;
					char c;
					}
					code; 
			
		
	



The notation for accessing a union member that is nested inside a structure remains the same as for the nested structure.In effect,a union creates a storage location that can be used by one of its members at a time. When a different number is assigned to a new value the new value supercedes the previous members value. Unions may be used in all the places where a structure is allowed.